Python: talk to bash via Popen

Use Popen to start bash. Then pipe stdout,stderr,stdin to be able to read and write to these handles. Write ‘ls’ to stdin followed by an enter. Calling flush is important, without it nothing happens.

#!/usr/bin/env python3

import subprocess

def main():
    cmd = 'bash'
    process = subprocess.Popen(cmd,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE,
                            universal_newlines=True)

    process.stdin.write('ls\n')
    process.stdin.flush()

    for line in iter(process.stdout.readline, b''):
        print(line, end='')


if __name__ == '__main__':
    main()

2 thoughts on “Python: talk to bash via Popen”

  1. No unfortunately I never found the solution… I kept on deleteing /var/lib/docker after every reboot (I only reboot like twice a month..)
    Eventually the problem disappeared in a newer version.

Leave a Reply

Your email address will not be published. Required fields are marked *