0

I run the following command from my bash script:

myProgram --name test1 --index 0

But now I want to run it from within a python script so I have tried the following:

#!/usr/bin/python
from threading import Thread
import time
import subprocess

print "hello Python"

subprocess.Popen("myProgram --name test1 --index 0")

But I get the error:

hello Python
Traceback (most recent call last):
File "./myPythonProgram.py", line 8, in <module>
subprocess.Popen("myProgram --name test1 --index 0")
File "/usr/lib64/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

Is the correct way to call this??

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • `subprocess.Popen("myProgram --name test1 --index 0", shell=True)`. or `subprocess.Popen(['myProgram', '--name', '1', '--index', '0'])` – Łukasz Rogalski Feb 09 '16 at 12:33

2 Answers2

2

You need to pass the command as a list:

subprocess.Popen("myProgram --name test1 --index 0".split())

Edit:

str.split() would not take into account the shell metacharacters/tokens, hence is insecure. You should use shlex.split() instead:

import shlex

command = shlex.split("myProgram --name test1 --index 0")
subprocess.Popen(command)
heemayl
  • 39,294
  • 7
  • 70
  • 76
2

You need to pass it as a list or you need to give an argument as shell=True

Try this:

output = subprocess.Popen("myProgram --name test1 --index 0", shell=True, universal_newlines=True)
out, err = output.communicate()

print(out)

The universal_newlines argument gives you output as a string without changing a newline in your output to a \n.

If you don't want to store the output in a variable and just want to get the output in the console, try subprocess.call() or, subprocess.run() if you have Python 3.5

Prashanth
  • 183
  • 6
  • 15