5

Code:

import subprocess

process = subprocess.Popen('echo 5')

Error:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    process = subprocess.Popen('echo 5')
  File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1238, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Can someone please advise what is the issue with the above code?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Raman
  • 665
  • 1
  • 15
  • 38
  • 1
    `Popen` expects list `["ls", "-lrt"]` (if you don't use `shell=True`) - check in documentation. – furas Nov 16 '16 at 07:13

2 Answers2

5

rewrite the code as follows

import subprocess

process = subprocess.Popen(['echo', '5'])

command should be a list

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Mr. A
  • 1,221
  • 18
  • 28
2

You have to specify executable and arguments either as a list:

subprocess.Popen(['echo', '5'])

or as a string and set shell=True:

subprocess.Popen('echo 5', shell=True)

The first is recommended, as it handles needed escaping for you. The second simply passes the string to the shell. According to subprocess docs:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
M. Volf
  • 1,259
  • 11
  • 29