Subprocess with a Python Session?

Nick Craig-Wood nick at craig-wood.com
Wed Dec 6 01:33:24 EST 2006


Calvin Spealman <ironfroggy at gmail.com> wrote:
>  No matter what I do I cant get the following code to do what I expect.
>  I hadn't used subprocess t o read and write to pipes of a
>  still-running app, and I just can't seem to get it right. What gives?
> 
>  import subprocess
> 
>  p = subprocess.Popen("python", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
>  p.stdin.write('print 10\n')
>  assert p.stdout.readline() == '10\n'

To read and write to a still running app, you'll want to use pexpect
probably.

  http://pexpect.sourceforge.net/

>>> import pexpect
>>> p = pexpect.spawn("python")
>>> p.expect(">>>")
0
>>> p.sendline("print 10\n")
10
>>> p.readline()   
' print 10\r\n'
>>> p.readline()
'10\r\n'
>>> 

Note that running python under pexpect puts it into interactive
mode.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list