如何在Python中运行BASH内置命令?

20 投票
2 回答
8766 浏览
提问于 2025-04-16 14:35

有没有办法在Python中运行BASH内置命令呢?

我试过:

subprocess.Popen(['bash','history'],shell=True, stdout=PIPE)

subprocess.Popen('history', shell=True, executable = "/bin/bash", stdout=subprocess.PIPE)

os.system('history')

还有很多不同的尝试。我想运行 history 或者 fc -ln

2 个回答

17
subprocess.Popen(["bash", "-c", "type type"])

这段代码是让bash(一个命令行工具)去执行一个字符串 type type,这个字符串会运行内置命令 type,并且把 type 作为参数传给它。

输出结果是:type is a shell builtin

-c 后面的部分必须是一个完整的字符串。像这样写是行不通的:["bash", "-c", "type", "type"]

19

我终于找到一个有效的解决办法了。

from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, 
    stderr=STDOUT)

output = event.communicate()

谢谢大家的建议。

撰写回答