【问题标题】:How to use the subprocess.check_output comand correctly如何正确使用 subprocess.check_output 命令
【发布时间】:2016-10-07 13:23:02
【问题描述】:

我想用不同的参数执行 shell 脚本generateLicense.sh。我是这样做的:

License = subprocess.check_output(['./generateLicense.sh -firstargument 1 -secondargument 2 -thirdargument 3'])

shell 脚本与启动 shell 脚本的文件位于同一文件夹中,但我总是收到此错误:

OSError: [Errno 2] No such file or directory

【问题讨论】:

    标签: python shell subprocess


    【解决方案1】:

    按照您尝试的方式使用check_output,每个命令都必须是您传递的列表中的一个项目。所以,你应该拥有的是:

    License = subprocess.check_output(['./generateLicense.sh', '-firstargument', '1', '-secondargument', '2', '-thirdargument', '3'])
    

    这里是您的问题的复制,使用不同的命令来展示当您将多参数命令作为列表中的单个字符串传递给check_output 时发生的情况:

    >>> import subprocess
    >>> subprocess.check_output(["ls -a"])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
        process = Popen(stdout=PIPE, *popenargs, **kwargs)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
        errread, errwrite)
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
        raise child_exception
    OSError: [Errno 2] No such file or directory
    

    在 Python 3 中执行此操作实际上会得到更连贯的内容:

    FileNotFoundError: [Errno 2] No such file or directory: 'ls -a'
    

    【讨论】:

    • 许可证 = subprocess.check_output(['./generateLicense.sh', '-firstargument', '1', '-secondargument', '2', '-thirdargument', '3'] ) 仍然会抛出同样的错误
    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2017-05-20
    • 2020-11-12
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多