在Python脚本中运行bash命令

2024-06-17 12:49:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

有人知道允许这种情况发生的模块/函数吗?我找不到。在


Tags: no脚本bashoutputfile1lscatfile2
1条回答
网友
1楼 · 发布于 2024-06-17 12:49:05

^{}模块包含所有问题的答案。尤其是,^{}似乎正是您想要的。页面示例:

>>> 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

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want access to other shell features such as filename wildcards, shell pipes and environment variable expansion.

相关问题 更多 >