【问题标题】:subprocess checkouput OSError: [Errno 2] No such file or directorysubprocess checkouput OSError: [Errno 2] No such file or directory
【发布时间】:2018-07-24 01:58:22
【问题描述】:

下面是示例代码:

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 命令输出的最佳方法是什么

【问题讨论】:

    标签: python linux python-2.7 subprocess


    【解决方案1】:

    在这种情况下有几个选项,用于传递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 ...'
    

    只是为了跟进mariis 的回答。 python.org 上的subprocess docs 提供了有关为什么您可能希望从几个选项中选择一个的更多信息。

    args 是所有调用所必需的,应该是字符串或序列 程序参数。提供一系列参数通常是 首选,因为它允许模块处理任何需要的 转义和引用参数(例如,允许文件中的空格 名称)。如果传递单个字符串,shell 必须是 True(请参阅 下面),否则字符串必须简单地命名要执行的程序 不指定任何参数。

    (添加重点)

    虽然为此添加shell=True 是可以的,但建议避免,因为将'df -h' 更改为['df', '-h'] 并不是很困难,而且是一个养成的好习惯,只有在你真的使用shell 时才使用需要。正如文档还添加的那样,红色背景不少:

    警告。 执行包含来自 不受信任的来源使程序容易受到 shell 注入的影响,这是一种 严重的安全漏洞,可能导致任意命令执行。 因此,强烈建议使用shell=True 从外部输入构造命令字符串的情况

    【讨论】:

      【解决方案2】:

      我推荐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)
      

      【讨论】:

        【解决方案3】:

        您应该提供check_output 参数作为列表。 这有效:

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

        【讨论】:

        • 请注意,您必须添加shell=True 作为check_output 的参数才能执行shell 命令。
        猜你喜欢
        • 2016-06-07
        • 2017-07-05
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 2018-01-21
        • 1970-01-01
        • 2015-05-06
        相关资源
        最近更新 更多