[英]Passing dictionary as an argument to another python script
I want to pass a dictionary as an argument to a separate python script as shown below: 我想将字典作为参数传递给单独的python脚本,如下所示:
dict1= {'appid':'facebook'}
subprocess.call('python mypython.py -o' + dict1, shell=True) (Also tried with os.system)
Contents of mypython.py: 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: 现在,当我使用str将dict对象转换为字符串时,我遇到了另一个问题:
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. 它在:之后(11之前)增加了一个额外的空间,因此它失败了。 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? 有人可以建议我如何将字典作为参数传递给另一个脚本吗?
您可以将dict转换为字符串( str(dict1)
),然后使用this在另一个类中对其进行解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.