En Thu, 25 Sep 2008 09:49:31 -0300, Almar Klein <[EMAIL PROTECTED]>
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_prompt(stdout):
while True:
line = stdout.read(4)
if line==sys.ps1:
yield line
return
else:
line += stdout.readline()
yield line
def print_output(stdout):
for line in read_until_prompt(stdout):
sys.stdout.write(line)
s = subprocess.Popen(["python", '-i'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE)
stdout = s.stdout
stdin = s.stdin
print_output(stdout)
stdin.write("dir()\n")
print_output(stdout)
stdin.write("def foo(x):\n")
stdin.write(" for i in range(x):\n")
stdin.write(" print i\n")
stdin.write("\n")
stdin.write("foo(5)\n")
print_output(stdout)
stdout.close()
stdin.close()
s.wait()
print "bye"
--- begin ---
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list