subprocess.Popen howto?

Øystein Johansen (OJOHANS) OJOHANS at StatoilHydro.com
Thu May 7 06:54:45 EDT 2009


Hi,
 
I have problems understanding the subprocess.Popen object. I have a iterative calculation in a process running and I want to pipe the output (stdout) from this calculation to a Python script.
 
Let me include a simple code that simulates the calculating process:
/* This code simulates a big iterative calculation */
#include <stdio.h>
#include <math.h>
 
int main()
{
 float val[2] = { M_PI, M_E };
 int i;
 
 for ( i = 0; i < 2 i++) {
  sleep( 15 );   /* It's a hard calculation. It take 15 seconds */
  printf("Value: %5.6f\n", val[i] );
  fflush( stdout );
 }
 return 0;
}
 
let's compile this to mycalc: gcc -o mycalc calc.c ... (untested code)
 
In C I have this code which starts the mycalc process and handles the output from it:
 
#include <stdio.h>
#include <assert.h>
#define BUF_SIZE 256
 
int main()
{
 FILE *pip;
 char line[BUF_SIZE];
 
 pip = popen("mycalc", "r");
 assert( pip != NULL );
 
 while ( fgets( line, BUF_SIZE, pip )) {
  printf( "Hello; I got: %s \n", line );
  fflush( stdout );
 }
 pclose( pip );
 return 0;
}

How can I make such while-loop in Python? I assume I should use subprocess.Popen(), but I can't figure out how?
 
-Øystein
 
 


-------------------------------------------------------------------
The information contained in this message may be CONFIDENTIAL and is
intended for the addressee only. Any unauthorised use, dissemination of the
information or copying of this message is prohibited. If you are not the
addressee, please notify the sender immediately by return e-mail and delete
this message.
Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090507/e8a12079/attachment.html>


More information about the Python-list mailing list