如何正确使用subprocess.check_output命令

时间:2016-10-07 13:23:02

标签: python shell subprocess

我想用不同的参数执行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

1 个答案:

答案 0 :(得分:0)

按照您尝试的方式使用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'