python调用外部程序的非阻塞方式 [英] python call external program non-blocking way

查看:553
本文介绍了python调用外部程序的非阻塞方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在python中调用外部程序,而不必等待其执行完成?

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 &")

通常,如果我在bash shell中调用external_program &,它将作为后台进程执行. 我该如何在python中执行此操作?对于我的特殊情况,创建另一个线程是行不通的.在完成主要的python scrip之后,外部程序应继续执行.

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.

推荐答案

是的,请使用 subprocess模块.例如:

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()

这篇关于python调用外部程序的非阻塞方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆