0

I am trying to write the codes to run a C executable using Python.

The C program can be run in the terminal just by calling ./myprogram and it will prompt a selection menu, as shown below:

1. Login
2. Register

Now, using Python and subprocess, I write the following codes:

import subprocess
subprocess.run(["./myprogram"])

The Python program runs but it shows nothing (No errors too!). Any ideas why it is happening?

When I tried:

import subprocess
subprocess.run(["ls"])

All the files in that particular directory are showing. So I assume this is right.

  • try `p=subprocess.Popen(["./myprogram"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)` and use `stdout_data,stderr_data=p.communicate()`. this will return a tuple of stderr and stdout data. then just print the data in stdout (as a file) – Adam Jul 13 '20 at 10:14
  • Thanks @Adam. In this case, how can I input the value to select from the menu? – Stuart Peterson Jul 13 '20 at 10:37
  • If your program `myprogram`, interacts with the user via `stdin`, then you cant, because you have binded the child process stdin to `subprocess.PIPE`, for ipc with the parent process. if `myprogram` dont need to interact with user inputs, then consider to push those inputs from parent to child via the stdin pipe. – Adam Jul 13 '20 at 10:41
  • is there any workaround for this? So that I cant interact with C program using Python? – Stuart Peterson Jul 13 '20 at 10:43

2 Answers2

1

You have to open the subprocess like this:

import subprocess
cmd = subprocess.Popen(['./myprogram'], stdin=subprocess.PIPE)

This means that cmd will have a .stdin you can write to; print by default sends output to your Python script's stdout, which has no connection with the subprocess' stdin. So do that:

cmd.stdin.write('1\n')  # tell myprogram to select 1

and then quite probably you should:

cmd.stdin.flush()  # don't let your input stay in in-memory-buffers

or

cmd.stdin.close()  # if you're done with writing to the subprocess.

PS If your Python script is a long-running process on a *nix system and you notice your subprocess has ended but is still displayed as a Z (zombie) process, please check that answer.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • Thanks. It works. The problem now is that it seems like the C program can't take the input. It just straight away prompting saying I am not entering the right input. – Stuart Peterson Jul 13 '20 at 10:25
  • When you run the C program, do you see a menu printed and then a prompt to enter the choice and return (case A), or does it fill the terminal window, with colours and stuff, and waits fot a key press (case B)? If case A, then we'll try to understand; if case B, perhaps try writing a plain '1' instead of '1\n' and flush, but it's not certain it will work. – tzot Jul 14 '20 at 14:17
0

Maybe flush stdout?

print("", flush=True,end="")
JCWasmx86
  • 3,473
  • 2
  • 11
  • 29