Interacting with bash from python

前端 未结 4 2036
心在旅途
心在旅途 2020-12-01 14:24

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 o

4条回答
  •  孤街浪徒
    2020-12-01 15:17

    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'
    >>> 
    

提交回复
热议问题