如何从 Python 异步运行外部命令? [英] How can I run an external command asynchronously from Python?

查看:25
本文介绍了如何从 Python 异步运行外部命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 Python 脚本异步运行 shell 命令.我的意思是我希望我的 Python 脚本在外部命令关闭并执行它需要做的任何事情时继续运行.

I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.

我读过这篇文章:

在 Python 中调用外部命令

然后我去做了一些测试,看起来 os.system() 可以完成这项工作,前提是我在最后使用 &命令,这样我就不必等待它返回.我想知道的是,这是否是完成此类事情的正确方法?我尝试了 commands.call() 但它对我不起作用,因为它会阻止外部命令.

I then went off and did some testing, and it looks like os.system() will do the job provided that I use & at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried commands.call() but it will not work for me because it blocks on the external command.

请告诉我是否建议使用 os.system() 或者我是否应该尝试其他方法.

Please let me know if using os.system() for this is advisable or if I should try some other route.

推荐答案

subprocess.Popen 正是您想要的.

subprocess.Popen does exactly what you want.

from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

(编辑以完成评论中的答案)

(Edit to complete the answer from comments)

Popen 实例可以做各种其他的事情,就像你可以poll() 看看它是否还在运行,你可以communicate() 与它在 stdin 上发送数据,并等待它终止.

The Popen instance can do various other things like you can poll() it to see if it is still running, and you can communicate() with it to send it data on stdin, and wait for it to terminate.

这篇关于如何从 Python 异步运行外部命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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