Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interacting with bash from python

I've been playing around with Python's subprocess module and I wanted to do an "interactive session" with bash from python. I want to be able to read bash output/write commands from Python just like I do on a terminal emulator. I guess a code example explains it better:

>>> proc = subprocess.Popen(['/bin/bash'])
>>> proc.communicate()
('user@machine:~/','')
>>> proc.communicate('ls\n')
('file1 file2 file3','')

(obviously, it doesn't work that way.) Is something like this possible, and how?

Thanks a lot

like image 596
justinas Avatar asked Mar 12 '12 19:03

justinas


People also ask

Can you call a bash script from Python?

Executing bash scripts using Python subprocess moduleWe can do it by adding optional keyword argument capture_output=True to run the function, or by invoking check_output function from the same module. Both functions invoke the command, but the first one is available in Python3.

How do you trigger 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.

What does %% bash do in Python?

This command will give you the core project you are working on. The export command in bash is used to set values to environmental variables. In the case it basically sets the value of an environmental variable called PROJECT and the echo just echoes the value back to the console.


1 Answers

Try with this example:

import subprocess

proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('ls -lash')

print stdout

You have to read more about stdin, stdout and stderr. This looks like good lecture: http://www.doughellmann.com/PyMOTW/subprocess/

EDIT:

Another example:

>>> process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> process.stdin.write('echo it works!\n')
>>> process.stdout.readline()
'it works!\n'
>>> process.stdin.write('date\n')
>>> process.stdout.readline()
'wto, 13 mar 2012, 17:25:35 CET\n'
>>> 
like image 141
Adam Avatar answered Oct 08 '22 02:10

Adam