将字典作为命令行参数传递

时间:2016-06-10 06:07:16

标签: python python-2.7 dictionary command-line-arguments

文件 - 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()

文件 - b.py

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

执行a.py时,我收到以下错误:

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}']

我试过json&amp; cPickle两者都不起作用。

2 个答案:

答案 0 :(得分:1)

只需在字典中添加双引号:

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

答案 1 :(得分:0)

Json是用于将python字典序列化为字符串的最可靠格式。

# 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'}