0

I want to pass a dictionary as an argument to a separate python script as shown below:

dict1= {'appid':'facebook'}
subprocess.call('python mypython.py -o' + dict1, shell=True) (Also tried with os.system)

Contents of mypython.py:

parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument("-o", dest="dict1")
args = parser.parse_args()
if args.dict1:
    op1 = args.dict1
    print op1

Traceback details:

python parent.py
Traceback (most recent call last):
  File "parent.py", line 52, in <module>
    sys.exit(main())
  File "mypython.py", line 30, in main
    subprocess.call('python mypython.py -o' + dict1, shell=True)
TypeError: cannot concatenate 'str' and 'dict' objects

Now when I convert the dict object to string using str, I hit another issue:

dict1={2:11}
tostr=str(dict1)
print (tostr)
os.system('python mypython.py -o '+tostr)

python parent.py
{2: 11}
usage: mypython.py [-h] [-o DICT1]
mypython.py: error: unrecognized arguments: 11}

It adds an extra space after : (before 11) and hence it fails. Only workaround is my input is a string:

dict1="{2:11}"
os.system('python mypython.py -o '+dict1)

It works as expected in the above case.

Can someone suggest me how to pass a dictionary as an argument to another script?

Rishabh Shah
  • 1
  • 1
  • 1
  • Why are you doing this via `subprocess`? – jonrsharpe Mar 17 '15 at 16:46
  • 2
    It looks like that you're trying to find a workaround on how to call a function which lies inside file A from file B. Please [read up on the Python tutorial section on modules](https://docs.python.org/3/tutorial/modules.html). That's the far better solution to your (presumed) problem. – Carsten Mar 17 '15 at 16:48

1 Answers1

0

You could cast the dict to a string (str(dict1)) and then parse it in the other class with this.

Community
  • 1
  • 1
Anselm Scholz
  • 478
  • 9
  • 20