subprocess module

T

Tim Roberts

placid said:
Hi all,

If someone could give me an example of creating a subprocess (on
Windows) using the subprocess module and Popen class and connecting to
its stdout/stdin file handles. I googled for a bit but the only example
i found was here ;

"Use the source, Luke." The best examples of the use of subprocess are
contained in the introductory comments in the module itself.
 
Joined
May 2, 2008
Messages
1
Reaction score
0
Subprocess read and write

I used the examples from the documentation. I was able to get it to write to the process, but I'm having trouble getting it to read.

I'm having it call an executable I wrote in C++. Here's the source:
Code:
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[]){
        string pizza;
        [B]cout<<"hello, type something"<<endl;[/B]
        cin>>pizza;
        cout<<"You typed "<<pizza<<endl;
}

When I just run the executable it works as expected.

Here's my python script:
Code:
#!/usr/bin/env python

import subprocess

pizza = subprocess.Popen("./hello",stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
print "opened"
[B]print pizza.stdout.read()[/B]
print "writing 'hello' to ./hello subprocess"
pizza.stdin.write("hello")
print "wrote 'hello' to ./hello subprocess"
print pizza.stdout.read()

So, when I run ./subprocesstest.py it should run the executable, read from its stdout, write 'hello' to its stdin, then read its stdout again. Unfortunately it gets stuck when it tries to read. The Bold portion of the two code segments are portions I tried commenting out and trying it. This makes it so it writes to the ./hello subprocess before reading from it. That appears to have worked, as it then outputs:
opened
writing 'hello' to ./hello subprocess
wrote 'hello' to ./hello subprocess

whereas with them uncommented it outputs:
opened

So, it's getting stuck every time it tries to read. Any ideas why?

Thanks,

Brett Bretterson
 

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

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top