Khobaib Zaamout
Khobaib Zaamout

Reputation: 11

Python subprocess.run with stderr=subprocess.PIPE redirects input(text)

I wrote a program (myProg.py) that uses subprocess module to run other python programs through the run function. I noticed that arg in input(arg) statements in these other python programs are not being displayed to the console (stdout), while args in print(args) are displayed properly. This only happens when I run my program through console. This does not happen when I run my program through LiClipse.

Here is the simplest way to replicate this situation:

Using python 3.6.2, and windows 10

  1. create a python program containing the following two lines and save it as someProgram.py:

a = input("Enter anything") print("a has: " + a)

  1. open cmd, type: python
  2. type: import subprocess
  3. type: subprocess.run(["python", "path..to..someProgram.py"], stderr=subprocess.PIPE)
  4. No ouptut so far but the interpreter is waiting on input... type something and hit Enter.
  5. You will see the output from the print statement.

If you remove , stderr=subprocess.PIPE you will see the correct outputs.

Now, save the code from steps 2 & 3 in another file, call it myProg.py in the same folder as someProgram.py. Run myProg.py from LiClipse. You will find that the myProg.py runs fine and produces the correct outputs.

My questions are:

  1. Why is this problem with subprocess.run happening
  2. How can I solve it
  3. Why would there be a difference between running code through commandline and through an IDE.

Upvotes: 1

Views: 586

Answers (1)

georgexsh
georgexsh

Reputation: 16624

input function print prompt text to stderr, this is a known issue

you redirected stderr, therefore prompt text not shown, when you run from LiClipse, stderr not get redirected.

you could output prompt by your self, like:

print("Enter anything", end='')
a = input()

alternatively, import readline module before input, then input will use GNU readline lib (if you have), which prints to stdout. While in your case, the program runs as a subprocess, you could still achieve this:

python -c "import readline; import runpy; runpy.run_path('/path/to/program.py')"

Upvotes: 1

Related Questions