简体   繁体   English

在 Python 中运行 BASH 内置命令?

[英]Run BASH built-in commands in Python?

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 history or fc -ln .我想运行historyfc -ln

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.谢谢大家的意见。

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

this calls bash and tells bash to run the string type type , which runs the builtin command type on the argument type .这个电话bash和告诉Bash运行字符串type type ,它运行的内置命令type的参数type

output: type is a shell builtin输出: type is a shell builtin

the part after -c has to be one string. -c之后的部分必须是一个字符串。 this will not work: ["bash", "-c", "type", "type"]这将不起作用: ["bash", "-c", "type", "type"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM