Python:如何执行外部程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4412852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:38:52  来源:igfitidea点击:

Python: How to execute an external program

pythonsubprocess

提问by Kennedy

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?

但它会停止我的程序,直到执行的程序停止/关闭。有没有办法让我的程序在外部程序执行后继续运行?

采纳答案by Wesley

Consider using the subprocessmodule.

考虑使用subprocess模块。

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

subprocess产生一个新进程,您的外部应用程序在其中运行。您的应用程序在其他应用程序运行时继续执行。

回答by Ignacio Vazquez-Abrams

You want subprocess.

你要subprocess

回答by Keith

You could use the subprocessmodule, 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.

你可以使用模块,而是使用os.system也会起作用。它通过一个 shell 工作,所以你只需要在你的字符串末尾加上一个“&”。就像在交互式 shell 中一样,它将在后台运行。

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

但是,如果您需要从中获得某种输出,您很可能希望使用 subprocess 模块。

回答by Martin Thoma

You can use subprocessfor that:

你可以使用subprocess

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
                          )