By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,959 Members | 2,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,959 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.