Subprocess.Popen does not give output

Question:

I have the following code:

from subprocess import Popen, PIPE
if os.path.isfile('../'):
    cmd = os.path.join(os.getcwd(), '../')
    proc = Popen(["python3", "-m", cmd], stdout=PIPE, stderr=PIPE)
    progRunning = True
    while progRunning:
        try:
            output, error = proc.communicate()
        except KeyboardInterrupt:
            print("Program Forcequit")
            progRunning = False
            proc.kill()
    print('Process finished')

Where ../ is the directory to a file. This program is supposed to run ../ and stop itself when it receives a KeyboardInterrupt. However, when I try to run this code,
print statements do not work. Here is the code in the ../ to test:

test.py
from time import *
while True:
    sleep(1)
    print("Hello World")

I am expecting an output of Hello World! every 1 second. I instead get no output. How do I fix this?

Asked By: PythonDudeLmao

||

Answers:

There are several things wrong with this script. Firstly, the condition os.path.isfile('../') is always false, because .. is a directory, not a file. It should be os.path.isfile('../test.py'). Secondly, you should remove the -m option in the python call, because this loads test.py as a module, but does not execute it, so the script is never started. Thirdly, communicate is blocked until your script has finished, and the output is buffered, so nothing happens until the buffer is full (which can take quite some time). And finally, the output is put in the variable output, so in order to write the output to screen you should also add a print(output) in your main script.

I am wondering if running the test.py as an external python script is really required for your needs. Most probably you can better import as a normal python module

Answered By: Eelco van Vliet

As Eelco pointed out, Communicate blocks until process completion, So if u want to read and print the output of the child process try

while True:
    lines = proc.stdout.readlines()
    for line in lines:
        print (line)
Answered By: Abhilash Kar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.