在Python脚本中运行bash命令

在Python脚本中运行bash命令,python,bash,interpreter,Python,Bash,Interpreter,我想使用Python创建一个简单的“virtualbash”脚本,它接收命令并返回stdio输出。大概是这样的: >>> output = bash('ls') >>> print output file1 file2 file3 >>> print bash('cat file4') cat: file4: No such file or directory 有人知道允许这种情况发生的模块/功能吗?我找不到答案。模块包含您所有问题的答案。

我想使用Python创建一个简单的“virtualbash”脚本,它接收命令并返回stdio输出。大概是这样的:

>>> output = bash('ls')
>>> print output
file1 file2 file3
>>> print bash('cat file4')
cat: file4: No such file or directory
有人知道允许这种情况发生的模块/功能吗?我找不到答案。

模块包含您所有问题的答案。特别是,它似乎正是你想要的。页面中的示例:

>>> 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
如果shell为True,则指定的命令将通过shell执行。如果您主要使用Python来实现它在大多数系统shell上提供的增强控制流,并且仍然希望访问其他shell功能,例如文件名通配符、shell管道和环境变量扩展,那么这将非常有用


如果他想要类似shell的行为,你可能需要提到
shell=True