1

I'm trying to run a shell command from python but as soon as I add a pipe, I get a "OSError: [Errno 2] No such file or directory" error. I tried a variety of things and even referenced grep directly at /bin/grep. Any idea what I'm doing wrong?

Works:

import subprocess
p = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
out, err = p.communicate()
print out

Doesn't Work:

import subprocess
p = subprocess.Popen(["ls | grep '20'"], stdout=subprocess.PIPE)
out, err = p.communicate()
print out

Displayed Error:

[OMITTED]$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    p = subprocess.Popen(["ls | grep '20'"], stdout=subprocess.PIPE)
  File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[OMITTED]$

Version: Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2

paullb
  • 4,293
  • 6
  • 37
  • 65

1 Answers1

1

The pipe | is a shell feature. If you want to use it, you have to use Popen with shell=True.

import subprocess
p = subprocess.Popen(["ls | grep '20'"], stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
print out

NOTE:

Warning Passing shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

Source: subprocess.Popen

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82