469,928 Members | 1,897 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,928 developers. It's quick & easy.

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

En Thu, 25 Sep 2008 09:49:31 -0300, Almar Klein <al*********@gmail.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_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

Sep 25 '08 #1
0 1720

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

25 posts views Thread by Ben | last post: by
4 posts views Thread by ketulp_baroda | last post: by
1 post views Thread by chanmy8 | last post: by
5 posts views Thread by Jason Smith | last post: by
9 posts views Thread by angel | last post: by
4 posts views Thread by =?ISO-8859-2?Q?Micha=B3_Bentkowski?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.