将字典作为参数传递给另一个python脚本

时间:2015-03-17 16:44:14

标签: python dictionary arguments

我想将字典作为参数传递给单独的python脚本,如下所示:

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

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

回溯详情:

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

现在,当我使用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}

它在:(在11之前)之后增加了一个额外的空间,因此它失败了。只有解决方法是我的输入是一个字符串:

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

在上述情况下,它的工作正常。

有人可以建议我如何将字典作为参数传递给另一个脚本吗?

1 个答案:

答案 0 :(得分:0)

您可以将字典转换为字符串(str(dict1)),然后使用this在另一个类中解析它。

相关问题