在 Python 中运行 BASH 内置命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5460923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run BASH built-in commands in Python?
提问by duanedesign
Is there a way to run the BASH built-in commands from Python?
有没有办法从 Python 运行 BASH 内置命令?
I tried:
我试过:
subprocess.Popen(['bash','history'],shell=True, stdout=PIPE)
subprocess.Popen('history', shell=True, executable = "/bin/bash", stdout=subprocess.PIPE)
os.system('history')
and many variations thereof. I would like to run historyor fc -ln.
及其许多变体。我想跑history或fc -ln。
回答by duanedesign
I finally found a solution that works.
我终于找到了一个有效的解决方案。
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()
Thank you everyone for the input.
谢谢大家的意见。
回答by lesmana
subprocess.Popen(["bash", "-c", "type type"])
this calls bash and tells bash to run the string type type, which runs the builtin command typeon the argument type.
这将调用 bash 并告诉 bash 运行字符串type type,该字符串type在参数上运行内置命令type。
output: type is a shell builtin
输出: type is a shell builtin
the part after -chas to be one string. this will not work: ["bash", "-c", "type", "type"]
后面的部分-c必须是一个字符串。这将不起作用:["bash", "-c", "type", "type"]

