ChrisAdams ChrisAdams - 10 months ago 30
Python Question

Passing dictionaries to a Python script through the command line

How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script.

The options I've come to are:

I) Build a module to parse a dictionary from a string (more in-depth than I had hoped to go).

II) Use a temporary file to write a pickle, and pass the file's name as an argument

III) Don't allow dictionaries, but handle key/value pairs (that is " keya valuea keyb valub")

The solution does not have to be user-friendly, but does need to be program friendly. The second program must be run as a separate process, due to security and resource concerns.


Aside from pickle, another option is ast.literal_eval, if your dictionaries only contain Python primitives.

>>> d = {3: 9, 'apple': 'orange'}
>>> s = str(d)
>>> s
"{3: 9, 'apple': 'orange'}"
>>> import ast
>>> x = ast.literal_eval(s)
>>> x
{3: 9, 'apple': 'orange'}