2

Possible Duplicate:
how to call a program from python without waiting for it to return

I'm writing a PyQt program that needs to start an external Windows executable. At that point the Python program should continue to run, never needing any contact with the exe file it started.

I have tried several variations such as:

process = subprocess.Popen(["vncviewer.exe"]); process.communicate()
subprocess.call("vncviewer.exe")
os.system("vncviewer.exe")
os.system("vncviewer.exe&")
os.system("start vncviewer.exe")

etc.

Using most any strategy, I can run the program successfully, but the Python script is then blocked until the program completes. The GUI is frozen and unusable.

How can I have Python start a completely separate and unrelated task, and then continue to run so that I can open other programs, and even end the Python script without affecting the programs it started?

Community
  • 1
  • 1
jbbarnes77
  • 119
  • 2
  • 10
  • 1
    See the same question: [how to call a program from python without waiting for it to return](http://stackoverflow.com/questions/2602052/how-to-call-a-program-from-python-without-waiting-for-it-to-return) – aleks_misyuk Aug 23 '12 at 21:00

2 Answers2

6

PyQt4.QtCore.QProcess.startDetached() executes the program independently in background:

QProcess.startDetached('vncviewer.exe')

Unlike a left alone subprocess.Popen() object as suggested by Dougal, a process started with this method continues to run even after the calling process has terminated.

In PyQt4 programs, prefer QProcess over subprocess. The former integrates into the Qt event loop and allows for asynchronous communication with the sub process via Qt signals.

Community
  • 1
  • 1
1

The documentation of subprocess.Popen.communicate() includes the phrase "Wait for process to terminate," so it shouldn't be surprising that it blocks.

If you just create the Popen object and then leave it alone, it should run asynchronously. You can then call process.poll() or process.wait() if you want to check on it. Note you should make sure it's done before letting the script terminate, otherwise the subprocess will be unceremoniously killed. To let the script exit without killing the subprocess, see the question linked by @aleks_misyuk in the comments.

Community
  • 1
  • 1
Danica
  • 28,423
  • 6
  • 90
  • 122