Search code examples
pythonsubprocesspopen

Python2 Popen in Windows


I was trying to execute a windows console exe program using Popen on python 2.

import subprocess

#
# Other codes
#

p = subprocess.Popen(path_of_exe, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

output = p.stdout.read()
print output
p.stdin.write('mystring')

The program prints Command> when the program executed. However, the output variable has nothing about the string. It is always an empty string.

If I change stdout=subprocess.PIPE to stdout=sys.stdout, it printed outputs.

However, I need to get the output to parse the result from my input. So, I want to grep the output was program. I'm not sure why the subprocess.PIPE doesn't work.

Also, when I changed to stdout=sys.stdout, its output printed Command> infinitely. The program should print the Command> only one time before I put string.

I also tried to get the output using p.communicate()[0], but it doesn't work.

I'm no idea with this behavior. When I worked in a Linux environment, there is no problem like that. I might think it is a problem of stdin or stdout buffer even though flush not worked.


Solution

  • I have tackled this problem before. Try and use this syntax when using Popn on Python2.

    p=subprocess.Popen([python(where your python is located), file name, args],stdout=PIPE).stdout.read()

    Let me know if this worked out for ya!