Re: what does "python -i" use as input stream (stdin)?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gabriel Genellina

    #1

    Re: what does "python -i" use as input stream (stdin)?

    En Thu, 25 Sep 2008 09:49:31 -0300, Almar Klein <almar.klein@gm ail.com>
    escribió:
    Hi,
    I want to start "python -i" from a subprocess and change its stdin
    stream,
    so I get control over the commands I feed the interpreter.
    >
    I thought just changing sys.stdin to my custom file-like object would
    suffice, but this does not work. Neither does changing sys.__stdin__.
    >
    I guess the interpreter got a reference to the original stdin (the Pipe)
    before
    I could change it, and is using that instead of sys.stdin.
    >
    Any thoughts how I can get the interpreter to use MY custom stream?
    Use subprocess.PIPE
    Usually the tricky part is to figure out exactly whether there is more
    input or not. With Python it's easy, use the ps1 prompt.

    --- begin ---
    import sys
    import subprocess

    def read_until_prom pt(stdout):
    while True:
    line = stdout.read(4)
    if line==sys.ps1:
    yield line
    return
    else:
    line += stdout.readline ()
    yield line

    def print_output(st dout):
    for line in read_until_prom pt(stdout):
    sys.stdout.writ e(line)

    s = subprocess.Pope n(["python", '-i'],
    stdout=subproce ss.PIPE,
    stderr=subproce ss.STDOUT,
    stdin=subproces s.PIPE)
    stdout = s.stdout
    stdin = s.stdin
    print_output(st dout)
    stdin.write("di r()\n")
    print_output(st dout)
    stdin.write("de f foo(x):\n")
    stdin.write(" for i in range(x):\n")
    stdin.write(" print i\n")
    stdin.write("\n ")
    stdin.write("fo o(5)\n")
    print_output(st dout)
    stdout.close()
    stdin.close()
    s.wait()
    print "bye"
    --- begin ---

    --
    Gabriel Genellina

Working...