daniel
daniel

Reputation: 35703

Async read console output with python while process is running

I want to run a long process (calculix simulation) via python.

As mentioned here one can read the console string with communicate().

As far as I understand the string is returned after the process is completed? Is there a possibility to get the console output while the process is running?

Upvotes: 4

Views: 1425

Answers (2)

rparent
rparent

Reputation: 628

This should work:

sp = subprocess.Popen([your args], stdout=subprocess.PIPE)
while sp.poll() is None: # sp.poll() returns None while subprocess is running
  output = sp.stdout # here you have acccess to the stdout while the process is running
  # Do stuff with stdout

Notice we don't call communicate() on subprocess here.

Upvotes: 1

Neel
Neel

Reputation: 21243

You have to use subprocess.Popen.poll to check process terminates or not.

while sub_process.poll() is None:
    output_line = sub_process.stdout.readline()

This will give you runtime output.

Upvotes: 2

Related Questions