在Python脚本中运行bash命令

use*_*941 2 python bash interpreter

我想使用Python创建一个简单的"虚拟bash"脚本,它接受命令并返回stdio输出.像这样的东西:

>>> output = bash('ls')
>>> print output
file1 file2 file3
>>> print bash('cat file4')
cat: file4: No such file or directory
Run Code Online (Sandbox Code Playgroud)

有没有人知道允许这种情况发生的模块/功能?我找不到一个.

Cla*_*diu 6

subprocess模块可以解决您遇到的所有问题.特别是,check_output似乎完全符合你的要求.页面中的示例:

>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'

>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
   ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Run Code Online (Sandbox Code Playgroud)

如果shell为True,则将通过shell执行指定的命令.如果您主要使用Python来提供大多数系统shell提供的增强控制流,并且仍然希望访问其他shell功能(如文件名通配符,shell管道和环境变量扩展),则此功能非常有用.