1

i would like to control a C program with a Python script. The C program look like this:

#include <stdio.h>
#include <stdlib.h>

void main(){
    int num;
    do{
        printf("insert a number: \ninsert 3 to exit\n");
        scanf("%d", &num);
        switch(num){
            case 1: {printf("you pressed 1\n");break;}
            case 2: {printf("you pressed 1\n");break;}
            default:{printf("you pressed another key\n");}
        }
    }while(num!=3);
}

and my python script is using subprocess:

   import subprocess
   p=subprocess.Popen('./Cprogram', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
   p.stdin.write('1')
   p.communicate()

and the result is that the python shell is blocked with the cursor on a empty line.

without the while in the c program the script works fine. How i could manage it ?

Thank you

user3734366
  • 69
  • 1
  • 8
  • p.communicate() blocks until there is `stdout` to read from. – user3467349 Jan 30 '15 at 21:14
  • 1
    @user3467349: incorrect. `p.communicate()` won't return until `Cprogram` exits. – jfs Jan 30 '15 at 21:53
  • After you fix the input, you have to fix the buffering issue, see [Python C program subprocess hangs at “for line in iter”](http://stackoverflow.com/q/20503671/4279) – jfs Jan 30 '15 at 21:58
  • unrelated: don't use `void main()`. [It is explicitly forbidden in C++. Standard C recommends either `int main(void)` or `int main(int argc, char *argv[])` form. Though Microsoft C describes it](http://stackoverflow.com/a/18721336/4279) – jfs Jan 30 '15 at 22:06

1 Answers1

-1

p.communicate() will run until the C program finishes execution. Since you haven't passed in a 3, your program has not finished its execution. Maybe you're looking for something like (edited per Sebastian's comment):

import subprocess

p=subprocess.Popen('./Cprogram', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('1\n')
p.stdin.write('3\n')
out, err = p.communicate()
print(out)
glglgl
  • 89,107
  • 13
  • 149
  • 217
russianfool
  • 362
  • 2
  • 16
  • 1
    your code writes `13`, not `1 3`. Use `out = p.communicate(b'1\n3')[0].decode()` instead. – jfs Jan 30 '15 at 21:55