我怎样才能从异步的Python运行外部命令? [英] How can I run an external command asynchronously from Python?

查看:507
本文介绍了我怎样才能从异步的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.

我看到这篇文章:

<一个href=\"http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python\">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-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 不正是你想要的。

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实例可以做各种各样的其他事情一样,你可以 调查( ) 它,看它是否仍在运行,并且可以<$c$c>communicate()用它发送数据的标准输入,并等待它终止。

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天全站免登陆