sandy_1111
sandy_1111

Reputation: 383

pass dictionary as command line argument

FILE - a.py

import os
toolObj = {
    'CLIENT_IP': u'10.193.xyz.xyz',
    'CMD_KEY': 8000,
    'CMD_WD': None,
    'CMD': u'date',
    'NUM_INSTANCE': '',
    'DURATION': -1,
    'TIME_OUT': '',
    'PORT': '',
    'CNFG_PARAM': '',
    'MSG_TYPE': '',
    'NUM_ITER': '',
    'CMD_HASH': '1475212'
}
print os.popen('python b.py %s'%toolObj).read()

FILE - b.py

import sys, ast<br>
print sys.argv
toolObj = ast.literal_eval(sys.argv[1])
print 'using ast', toolObj

On executing a.py i get the following error:

Traceback (most recent call last):
File "96_.py", line 16, in 
toolObj = ast.literal_eval(sys.argv[1])
File "/usr/local/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/local/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "", line 1
{CLIENT_IP:
^ SyntaxError: unexpected EOF while parsing
['96_.py', '{CLIENT_IP:', 'u10.193.xyz.xyz,', 'CMD_KEY:', '8000,', 'CMD_WD:', 'None,', 'CMD:', 'udate,', 'NUM_INSTANCE:', ',', 'DURATION:', '-1,', 'TIME_OUT:', ',', 'NUM_ITER:', ',', 'CNFG_PARAM:', ',', 'MSG_TYPE:', ',', 'PORT:', ',', 'CMD_HASH:', '1475212}']

I have tried json & cPickle both did not work.

Upvotes: 1

Views: 3281

Answers (2)

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23084

Json is the most reliable format to use for serializing a python dictionary to a string.

# b.py
import json, sys
toolObj = json.loads(sys.argv[1])
print toolObj

# a.py
import json, os
toolObj = dict(a=1, b='foo', c=None)
# using %r in the format string makes sure special characters are escaped.
cmd = 'python b.py %r' % json.dumps(toolObj)
# cmd is now:
# python b.py '{"a": 1, "c": null, "b": "foo"}'

print os.popen(cmd).read()
# output is:
# {u'a': 1, u'c': None, u'b': u'foo'}

Upvotes: 0

niemmi
niemmi

Reputation: 17273

Just add double quotes around the dictionary:

print os.popen('python b.py "%s"'%toolObj).read()

Upvotes: 1

Related Questions