Subprocess with a Python Session?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Calvin Spealman

    #1

    Subprocess with a Python Session?

    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.Pope n("python", stdout=subproce ss.PIPE, stdin=subproces s.PIPE)
    p.stdin.write(' print 10\n')
    assert p.stdout.readli ne() == '10\n'

    --
    Read my blog! I depend on your acceptance of my opinion! I am interesting!

  • Nick Craig-Wood

    #2
    Re: Subprocess with a Python Session?

    Calvin Spealman <ironfroggy@gma il.comwrote:
    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.Pope n("python", stdout=subproce ss.PIPE, stdin=subproces s.PIPE)
    p.stdin.write(' print 10\n')
    assert p.stdout.readli ne() == '10\n'
    To read and write to a still running app, you'll want to use pexpect
    probably.

    Download Pexpect - Pure Python Expect-like module for free. Pexpect is a Python module for spawning child applications; controlling them;

    >>import pexpect
    >>p = pexpect.spawn(" python")
    >>p.expect(">>> ")
    0
    >>p.sendline("p rint 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@craig-wood.com-- http://www.craig-wood.com/nick

    Comment

    Working...