Shell在Python中使用管道命令

Shell commands with a pipe in Python

本问题已经有最佳答案,请猛点这里访问。

我正在尝试从python运行shell命令,但一旦添加管道,就会出现"oserror:[errno 2]no such file or directory"错误。我尝试了很多方法,甚至直接在/bin/grep引用grep。知道我做错了什么吗?

作品:

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

不起作用:

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

显示的错误:

1
2
3
4
5
6
7
8
9
10
[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]$

版本:python 2.6.6(r266:84292,2014年1月22日,09:42:36)【GCC 4.4.7 20120313(Red Hat 4.4.7-4)】关于Linux2


管道|是一个外壳特征。如果你想使用它,你必须使用popen和shell=True

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

注:

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

来源:Subprocess.popen