繁体   English   中英

子进程签出OSError:[Errno 2]没有这样的文件或目录

[英]subprocess checkouput OSError: [Errno 2] No such file or directory

下面是示例代码:

from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
    output = check_output([x])

dh -h值的list1低于错误。

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_output参数作为列表。 这有效:

from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
    output = check_output(x.split())

我建议由kennethreitz编写的delegator及其包https://github.com/kennethreitz/delegator.py ,您可以轻松完成,并且API和输出都更简洁:

import delegator

cmds = ['df', 'df -h']
for cmd in cmds:
    p = delegator.run(cmd)
    print(p.out)

在这种情况下,有几种选择,用于传递cmdargs

# 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注入的攻击,这是一个严重的安全漏洞,可能导致任意命令执行。 因此, 强烈建议不要使用shell=True来从外部输入构造命令字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM