4

is there a way to call an external program inside python and don't wait for its execution to finish?

I tried this, but no luck:

os.system("external_program &")

Normally, if I call external_program & inside a bash shell it executes as a background process. How can I do it inside python? For, my special case, creating another thread does not work. After main python scrip is done, the external program should continue its execution.

Gokhan Ka
  • 49
  • 1
  • 2

2 Answers2

5

Yes, use the subprocess module. For example:

p = subprocess.Popen(['external_program', 'arg1', 'arg2'])
# Process is now running in the background, do other stuff...
...
# Check if process has completed
if p.poll() is not None:
    ...
...
# Wait for process to complete
p.wait()
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 1
    I tried this. It is still blocking. And, if it works, what happens if I don't wait at the end? Is it going to be killed? – Gokhan Ka Jun 07 '13 at 14:50
  • I realized that it actually works but the main script waits at the end. I need a complete independence from the main script. Is it possible? – Gokhan Ka Jun 07 '13 at 15:45
  • @GokhanKa: If you don't want the main script to wait, then don't call `wait()`, it's that simple. If you exit while the subprocess is still running, it will continue to run in the background. – Adam Rosenfield Jun 07 '13 at 18:12
  • 1
    I'm not calling wait(). It does not even execute sys.exit(0) after Popen call. If I call p.terminate(), it immediately terminates the subprocess and exits. How strange is this? – Gokhan Ka Jun 07 '13 at 22:08
  • Coming from a duplicate, I want to emphasize: replace `os.system("thing &")` with `p = subprocess.Popen(['thing'])` without the `&` (and without the shell) and do whatever else you want to do. `p` will exist and be running in the background because you created a subprocess, just like the shell does with `&` and you can eventually reap it with `p.wait()`. Things will be a little more complex and subtle if `thing` blocks because it is writing to a pipe or something, but there are other questions which explain this in more detail. – tripleee Feb 17 '17 at 08:12
2

Forget about os.system(). It is deprecated in favour of the subprocess module.

It provides a way to execute subprograms for almost every thinkable use case.

glglgl
  • 89,107
  • 13
  • 149
  • 217