subprocess.Popen howto?

Chris Rebert clp2 at rebertia.com
Thu May 7 18:54:39 EDT 2009


2009/5/7 Øystein Johansen (OJOHANS) <OJOHANS at statoilhydro.com>:
> 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?

import subprocess
subprocess.call(["./mycalc"]) # add `bufsize=-1` as argument to have
output be buffered
#process inherits our filehandles and writes directly to them
#.call() only returns once the process has exited

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list