Python 将字典作为命令行参数传递
文件-a.pyPython 将字典作为命令行参数传递,python,python-2.7,dictionary,command-line-arguments,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': '',
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()
import sys, ast<br>
print sys.argv
toolObj = ast.literal_eval(sys.argv[1])
print 'using ast', toolObj
文件-b.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()
import sys, ast<br>
print sys.argv
toolObj = ast.literal_eval(sys.argv[1])
print 'using ast', toolObj
我尝试了
json
&cPickle
但都不起作用。只需在字典周围加上双引号:
print os.popen('python b.py "%s"'%toolObj).read()
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'}
为什么不直接导入
b.py
?