Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 argparse / optparse or do I have to build my own parser?

like image 486
David Just Avatar asked Apr 08 '11 18:04

David Just


People also ask

Can you pass a dictionary as an argument in Python?

In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.

Can we pass list as command line argument in Python?

Can we pass list as an argument in Python? You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


1 Answers

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.

like image 57
Judge Maygarden Avatar answered Nov 15 '22 17:11

Judge Maygarden