Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run BASH built-in commands in Python?

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.

like image 368
duanedesign Avatar asked Mar 28 '11 15:03

duanedesign


People also ask

Can you run bash commands in Python?

Is there any way to execute the bash commands and scripts in Python? Yeah, Python has a built-in module called subprocess which is used to execute the commands and scripts inside Python scripts.

How do I run a bash file in Python?

Use subprocess. call() to execute a Bash script Call subprocess. call(file) to execute the Bash script file and return the exit code of the script.

How do I run a shell script in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

Can I run Linux command in Python?

Introduction. Python has a rich set of libraries that allow us to execute shell commands. The os. system() function allows users to execute commands in Python.


1 Answers

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.

like image 133
duanedesign Avatar answered Sep 29 '22 23:09

duanedesign