有没有一种方法可以从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
。
有没有一种方法可以从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
。
我终于找到了一个可行的解决方案。
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()
感谢大家的贡献。
subprocess.Popen(["bash", "-c", "type type"])
这会调用Bash,并告诉Bash运行字符串type type
,该字符串在参数type
上运行内置命令type
。
输出:type是一个shell内置命令
-c
后面的部分必须是一个字符串。 这样做是不起作用的:["bash", "-c", "type", "type"]
suprocess.run(['bash', '-c', 'command command-that-shouldnt-exist'], check=True)
正确地失败了,而 suprocess.run(['bash', '-c', 'command', 'command-that-shouldnt-exist'], check=True)
却可以正常工作。 - user3064538
sudo
后输入密码)非常有用。我认为pexpect可以满足这个需求。 - Ehtesh Choudhury