开发者

Python: Pass a generic dictionary as a command line arguments

I have a script that needs to take in the name of a file and a set of key=value pairs. The set of key=value pairs is not defined. They are dependent on the file that was passed in.

eg:

Script.py file1 bob=1 sue=2 ben=3  # file 1 needs bob, sue, and ben

Script.py file2 mel=1 gorge=3 steve=3 # file 2 needs mel, gorge, and steve

Is this possible with argpa开发者_运维技巧rse / optparse or do I have to build my own parser?


That should be fairly easy to parse yourself. Use of the helper libraries would be complicated by not knowing the keys in advance. The filename is in sys.argv[1]. You can build the dictionary with a list of strings split with the '=' character as a delimiter.

import sys
filename = sys.argv[1]
args = dict([arg.split('=', maxsplit=1) for arg in sys.argv[2:]])
print filename
print args

Output:

$ Script.py file1 bob=1 sue=2 ben=3
file1
{'bob': '1', 'ben': '3', 'sue': '2'}

That's the gist of it, but you may need more robust parsing of the key-value pairs than just splitting the string. Also, make sure you have at least two arguments in sys.argv before trying to extract the filename.


Hope this helps, instead of passing a dict you can pass an "escaped" json string as a command line argument

import optparse
import json

parser = optparse.OptionParser()
parser.add_option("-t", "--test", dest="test", action="store", type="string")
options, _ = parser.parse_args()
my_dict = json.loads(options.test)
print my_dict['key1']

then use it as so:

python test.py -t "{\"key1\":\"value1\",\"key2\":\"value2\"}"

this will output "value1"


Here is an example:

Example: 1:

# runline argument is : ./filename fname=sameer sname=ali age=29
import sys 

l = sys.argv[1:]

print(l)

l = ['fname=sameer', 'sname=ali', 'age=29']

for i in l:

    runarg = i.split('=')

    d[runarg[0]] = runarg[1]

print(d)

{'fname': 'sameer', 'sname': 'ali', 'age': '29'}

Example: 2

print(sys.argv[1:]

ouput: ['fname=sameer', 'sname=ali', 'age=29']

newlist = [x.split('=') for x in l] print(newlist)

output: [['fname', 'sameer'], ['sname', 'ali'], ['age', '29']]

newdict = dict(newlist)

print(newdict)

output: {'fname': 'sameer', 'sname': 'ali', 'age': '29'}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜