Python: passing multiple parameters to a popen command

I spent several hours trying to figure out how to pass in a few parameters to the python script that the subprocess should execute.

Script:

command = ['/usr/bin/python', '/tmp/script.py mcl=NULL mtp=data mnm=DS4INST \ mno=NULL mse=NULL mce=cll01'] result = subprocess.Popen(command, stdout = subprocess.PIPE, \ stderr = subprocess.PIPE) out, err = result.communicate() print out, err 

I get the following error message:

 python: can't open file '/tmp/script.py mcl=NULL mtp=data mnm=DS4INST mno=NULL \ mse=NULL mce=cll01': [Errno 2] No such file or directory 

However, when I execute the script directly from the shell

 /usr/bin/python /tmp/script.py mcl=NULL mtp=data mnm=DS4INST mno=NULL \ mse=NULL mce=cll01 

I get the desired output and no error message is generated.

Please inform.

+4
source share
1 answer

Try the following:

 command = ['/usr/bin/python', '/tmp/script.py', 'mcl=NULL', 'mtp=data', 'mnm=DS4INST', 'mno=NULL' 'mse=NULL', 'mce=cll01'] 

In your code, the second command element is considered as one single argument and interpreted as:

 /usr/bin/python "/tmp/script.py mcl=NULL mtp=data mnm=DS4INST mno=NULL mse=NULL mce=cll01" 

as simple as a long file name with spaces.

You must separate the arguments into separate elements of the command list.

+6
source

Source: https://habr.com/ru/post/1387531/


All Articles