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()