在Python脚本中运行bash命令

时间:2012-08-18 02:39:42

标签: 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

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

1 个答案:

答案 0 :(得分: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
  

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

相关问题