3

I have this python code

input()
print('spam')

saved as ex1.py

in interactive shell

>>>from subprocess import Popen ,PIPE
>>>a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE)

>>> a.communicate()

(b'', None)

>>>

why it is not printing the spam

R__raki__
  • 847
  • 4
  • 15
  • 30

3 Answers3

3

Input expects a whole line, but your input is empty. So there is only an exception written to stderr and nothing to stdout. At least provide a newline as input:

>>> a = Popen(['python3', 'ex1.py'], stdout=PIPE, stdin=PIPE)
>>> a.communicate(b'\n')
(b'spam\n', None)
>>> 
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • 2
    Thanks, I just added `stderr=PIPE` and then ran the program, and it caught the error as `(b'', b'Traceback (most recent call last):\r\n File "receive_from_sub.py", line 5, in \r\n input()\r\nEOFError: EOF when reading a line\r\n')` – R__raki__ Oct 13 '16 at 17:59
0

You are missing stderr piping:

from subprocess import Popen ,PIPE

proc = Popen(['python.exe','ex1.py'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
print(out, err)
I159
  • 29,741
  • 31
  • 97
  • 132
-1

What you're looking for is subprocess.check_output

sytech
  • 29,298
  • 3
  • 45
  • 86
  • 1
    Can you explain bit more that how your answer solves above question ? – R__raki__ Oct 13 '16 at 18:08
  • Hi Rakesh, did you see the question I linked to in the comments? [store the output of subprocess.popen call in a string](http://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string) This function is specifically for getting the output of another process. – sytech Oct 13 '16 at 18:11
  • While your answer might be correct, it's much better to explain why it's correct. That educates the OP helping them understand how to avoid the problem in the future. – the Tin Man Oct 14 '16 at 21:30