Search code examples
pythonbashsubprocess

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


Solution

  • 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:

    import subprocess
    
    process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    
    process.stdin.write(b'echo it works!\n')
    process.stdin.flush()
    print(process.stdout.readline()) # 'it works!\n'
    
    process.stdin.write(b'date\n')
    process.stdin.flush()
    print(process.stdout.readline()) # b'Fri Aug 30 18:34:33 UTC 2024\n'
    

    Since the stream is buffered by default you will need to either call flush after sending a command or disable buffering by setting bufsize=0 on the Popen call, both will work.
    You can check the subprocess.Popen documentation for more information on buffering.