Kennedy
Kennedy

Reputation: 2276

Python: How to execute an external program

How do I execute a program from within my program without blocking until the executed program finishes?

I have tried:

os.system()

But it stops my program till the executed program is stopped/closed. Is there a way to allow my program to keep running after the execution of the external program?

Upvotes: 3

Views: 30510

Answers (4)

Martin Thoma
Martin Thoma

Reputation: 136695

You can use subprocess for that:

import subprocess
import codecs

# start 'yourexecutable' with some parameters
# and throw the output away
with codecs.open(os.devnull, 'wb', encoding='utf8') as devnull:
    subprocess.check_call(["yourexecutable",
                           "-param",
                           "value"],
                          stdout=devnull, stderr=subprocess.STDOUT
                          )

Upvotes: 1

Wesley
Wesley

Reputation: 10872

Consider using the subprocess module.

subprocess spawns a new process in which your external application is run. Your application continues execution while the other application runs.

Upvotes: 12

Keith
Keith

Reputation: 43054

You could use the subprocess module, but the os.system will also work. It works through a shell, so you just have to put an '&' at the end of your string. Just like in an interactive shell, it will then run in the background.

If you need to get some kind of output from it, however, you will most likely want to use the subprocess module.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

You want subprocess.

Upvotes: 4

Related Questions