Run BASH built-in commands in Python?

£可爱£侵袭症+ 提交于 2019-12-17 09:47:37

问题


Is there a way to run the BASH built-in commands from Python?

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.


回答1:


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.




回答2:


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.

output: type is a shell builtin

the part after -c has to be one string. this will not work: ["bash", "-c", "type", "type"]



来源:https://stackoverflow.com/questions/5460923/run-bash-built-in-commands-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!