views:

61

answers:

2

When I execute a python script using subprocess.Popen(script, shell=True) in another python script, is it possible to alert python when the script completes running before executing other functions?

On a side note, can I get real-time output of the executed python script?
I can only get output from it doing command>output.txt but that's only after the whole process ends. stdout does not grep any ouput.

+2  A: 

When you create a subprocess with Popen, it returns a subprocess.Popen object that has several methods for accessing subprocess status and data:

  • You can use poll() to determine whether a subprocess has finished. None indicates that the process has ended.
  • Output from a script while its running can be retrieved with communicate().

You can combine these two to create a script that monitors output from a subprocess and waits until its ready as follows:

import subprocess

p = subprocess.Popen((["python", "script.py"]), stdout=subprocess.PIPE)

while p.poll() is None:
    (stdout, stderr) = p.communicate()
    print stdout
jsalonen
A: 

You want to wait for the Popen to end? have you tried simply this:

popen = subprocess.Popen(script, shell=True)
popen.wait()

Have you considered using the external python script importing it as a module instead of spawning a subprocess?

As for the real-time output: try python -u ...

tokland