简体   繁体   English

使用 JSON 字典作为参数的 Python 子进程

[英]Python subprocess using JSON dictionary as argument

I am trying to pass a JSON dictionary as an argument through the terminal using a subprocess .我想传递一个JSON字典作为通过终端使用的参数subprocess The dictionary keeps ending up different from when I pass it manually through the terminal.字典的结果与我手动通过终端传递时的结果不同。 I am using this code for the subprocess :我将此代码用于subprocess

subprocess.call("python ../power_supply_gui/PowerSupplyControl.py "+ "{\"CHANNEL\":\"d\",\"VOLT\":\"1\",\"CURRENTLIMIT\":\"1\",\"ENABLE\":\"1\"}",shell=True)

I should be getting this when I read it in the other program:当我在另一个程序中阅读它时,我应该得到这个:

{"CHANNEL":"d","VOLT":"1","CURRENTLIMIT":"1","ENABLE":"1"}

but instead, I am getting this:但相反,我得到了这个:

{CHANNEL:d,VOLT:1,CURRENTLIMIT:1,ENABLE:1}

This is how the program that is called is reading the argument and outputting it:这是被调用的程序读取参数并输出它的方式:

print sys.argv[1]
print type(sys.argv[1])
commandDictionary=json.loads(sys.argv[1]) 

The conversion of the dictionary to a json string puts a space after the colon which means that before the space and after the space are split up into different arguments.字典到 json 字符串的转换在冒号后放一个空格,这意味着空格前和空格后被分成不同的参数。 If you want this to work try removing the spaces with str(dictionary).replace(" ","") as the argument.如果您希望此方法起作用,请尝试使用str(dictionary).replace(" ","")作为参数删除空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM