subprocess.Popen() problem

7

7stud

I have this program:

mytest.py
--------------
myinput = raw_input("Enter input: ")

if myinput == "hello":
print "goodbye"
--------------

and I want to execute it using subprocess.Popen(). I tried the
following but it just hangs:

-----------
import subprocess

f = open("/Users/me/2testing/dir1/aaa.txt", "w")
my_path = "/Users/me/2testing/"
my_file = "mytest.py"

p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE,
stdout = f,
stderr = f,
cwd = my_path
)

f.close()

p.stdin.write("hello")
p.wait()

f.open("/Users/me/2testing/dir1/aaa.txt")
print f.read()
------------
 
J

Jerry Hill

p.stdin.write("hello")

You need to add the linefeed, otherwise your mytest.py process is
still waiting for you to finish typing. So, use this instead:

p.stdin.write("hello\n")
 
K

kyosohma

I have this program:

mytest.py
--------------
myinput = raw_input("Enter input: ")

if myinput == "hello":
print "goodbye"
--------------

and I want to execute it using subprocess.Popen(). I tried the
following but it just hangs:

-----------
import subprocess

f = open("/Users/me/2testing/dir1/aaa.txt", "w")
my_path = "/Users/me/2testing/"
my_file = "mytest.py"

p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE,
stdout = f,
stderr = f,
cwd = my_path
)

f.close()

p.stdin.write("hello")
p.wait()

f.open("/Users/me/2testing/dir1/aaa.txt")
print f.read()
------------

Never tried this, but I think you need to use the communicate method
detailed here:

http://docs.python.org/dev/lib/node537.html

If that doesn't work, you might look into using the threading module
and its methods. Or there could be a flush command that I can't
find...

Mike
 
7

7stud

You need to add the linefeed, otherwise your mytest.py process is
still waiting for you to finish typing. So, use this instead:

p.stdin.write("hello\n")

Arggh. Of course! Thanks
Never tried this, but I think you need to use the communicate method
detailed here:

Yes, communicate() will work too, but communicate reads stdout into a
string(i.e. into memory), and I don't want to do that. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,130
Members
46,689
Latest member
liammiller

Latest Threads

Top