Python 子进程检查输出OSError:[Errno 2]没有这样的文件或目录
下面是示例代码:Python 子进程检查输出OSError:[Errno 2]没有这样的文件或目录,python,linux,python-2.7,subprocess,Python,Linux,Python 2.7,Subprocess,下面是示例代码: from subprocess import check_output list1 = ['df', 'df -h'] for x in list1: output = check_output([x]) 获取dh-h值列表1的以下错误 File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output process = Popen(stdout=PIPE, *popenargs, **kwa
from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
output = check_output([x])
获取dh-h值列表1的以下错误
File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
在python2.7中读取linux命令输出的最佳方法是什么?您应该以列表的形式提供
check\u output
参数。
这项工作:
from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
output = check_output(x.split())
我推荐kennethreitz编写的
delegator
,使用他的软件包,您可以简单地执行,而且API和输出都更干净:
import delegator
cmds = ['df', 'df -h']
for cmd in cmds:
p = delegator.run(cmd)
print(p.out)
在这种情况下,对于传递
cmd
和args
的方式,有几个选项:
# a list broken into individual parts, can be passed with `shell=False
['cmd', 'arg1', 'arg2', ... ]
# a string with just a `cmd`, can be passed with `shell=False`
'cmd`
# a string with a `cmd` and `args`
# can only be passed to subprocess functions with `shell=True`
'cmd arg1 arg2 ...'
我只是想跟进他的回答。在python.org上有更多关于为什么您可能想要从几个选项中选择一个的信息
args
对于所有调用都是必需的,并且应该是字符串或序列
程序参数的定义。提供一系列参数通常是
首选,因为它允许模块处理任何需要的数据
转义和引用参数(例如,允许文件中有空格
名称)。如果传递单个字符串,则shell
必须为True
(请参阅
或者字符串必须简单地命名要执行的程序
不指定任何参数
(恩普西斯补充)
虽然添加shell=True
可以做到这一点,但建议避免,因为将'df-h'
更改为['df','-h']
不是很难,而且是一个好习惯,只有在确实需要时才使用shell。正如文档中所添加的,在红色背景下:
警告。
执行包含来自
不受信任的源使程序容易受到外壳注入的攻击
可能导致任意命令执行的严重安全缺陷。
出于这个原因,我们强烈反对在中使用shell=True
命令字符串由外部输入构造的情况
请注意,您必须添加
shell=True
作为check\u output
的参数来执行shell命令。