1

I have an exe file which accepts input from the keyboard, and returns a response based on the input text. When trying to read the output returned by the exe the python script freezes.

I'm running Windows 7 and python3.7. I've tried the answer at continuously interacting with .exe file using python.

from subprocess import Popen, PIPE

location = "C:\\Users\\file.exe"

p= Popen([location],stdin=PIPE,stdout=PIPE,stderr=PIPE, encoding="UTF8")
command='START'
p.stdin.write(command)
response=p.stdout.read()

I expect response to be populated with the output text, but instead the program freezes on that line.

The exe file that I want to interact with is here (EMBRYO file)

Oscar Torres
  • 71
  • 1
  • 10

2 Answers2

0

Call p.stdout.readline() instead of p.stdout.read(). That will give you one line at a time, instead of waiting for the process to close its stdout pipe. For more information, read the documentation.

Here's a more detailed example. Imagine this script is a replacement for your exe file:

# scratch.py
from time import sleep

for i in range(10):
    print('This is line', i)
    sleep(1)

Now I launch that script, and try to read its output:

from subprocess import Popen, PIPE, STDOUT

p = Popen(['python', 'scratch.py'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, encoding='UTF8')
for i in range(10):
    response = p.stdout.read()
    print('Response', i)
    print(response)

The results look like this: it waits ten seconds, then prints out the following:

Response 0
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9

Response 1

Response 2

Response 3

Response 4

Response 5

Response 6

Response 7

Response 8

Response 9

Now if I change it to readline(), I get this:

Response 0
This is line 0

Response 1
This is line 1

Response 2
This is line 2

Response 3
This is line 3

Response 4
This is line 4

Response 5
This is line 5

Response 6
This is line 6

Response 7
This is line 7

Response 8
This is line 8

Response 9
This is line 9
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
0

It seems like stdout wasn't being executed since the stdin wasn't being flushed, after calling p.stdin.flush() everything worked!

from subprocess import Popen, PIPE

location = "C:\\Users\\file.exe"

p= Popen(location,stdin=PIPE,stdout=PIPE,stderr=PIPE, encoding="UTF8")
command='START\n'
p.stdin.write(command)
p.stdin.flush()  # important
response=p.stdout.read()

Thanks to everyone who helped :)

Oscar Torres
  • 71
  • 1
  • 10
  • I could not repeat this in my python 3.8.8, windows 10, it is always freeze, anybody could repeat this recently? – adameye2020 Nov 08 '22 at 22:59