我需要从Python脚本异步运行shell命令。我的意思是,我希望我的Python脚本继续运行,同时外部命令关闭并执行它需要做的任何事情。
我读到了这篇文章:
然后我去做了一些测试,如果我在命令末尾使用&
,这样我就不必等待它返回,看起来os.system()
就可以完成这项工作。我想知道的是,这是否是完成这样一件事的合适方式?我尝试过commands.call()
,但它对我不起作用,因为它阻塞了外部命令。
请让我知道使用os.system()
是否可取,或者我是否应该尝试其他方法。
发布于 2009-03-11 22:05:33
subprocess.Popen
做的正是您想要的。
from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()
(编辑以完成评论中的答案)
Popen实例可以执行各种其他操作,比如您可以poll()
它以查看它是否仍在运行,您可以使用它communicate()
向它发送标准输入上的数据,并等待它终止。
发布于 2009-03-11 22:15:50
如果您希望并行运行多个进程,然后在它们产生结果时对其进行处理,则可以使用轮询,如下所示:
from subprocess import Popen, PIPE
import time
running_procs = [
Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]
while running_procs:
for proc in running_procs:
retcode = proc.poll()
if retcode is not None: # Process finished.
running_procs.remove(proc)
break
else: # No process is done, wait a bit and check again.
time.sleep(.1)
continue
# Here, `proc` has finished with return code `retcode`
if retcode != 0:
"""Error handling."""
handle_results(proc.stdout)
这里的控制流程有点复杂,因为我试图让它变得更小--您可以根据自己的喜好进行重构。:-)
这样做的好处是首先处理提前完成的请求。如果你在第一个运行的进程上调用communicate
,并且这个进程运行的时间最长,那么其他运行中的进程就会一直处于闲置状态,而你本可以处理它们的结果。
发布于 2020-04-16 23:52:48
Python 3 Subprocess Examples在“等待命令异步终止”中介绍了这一点。使用IPython
或python -m asyncio
运行此代码
import asyncio proc = await asyncio.create_subprocess_exec( ' ls ','-lha',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE) #在ls工作时执行其他操作#如果proc需要很长时间才能完成,CPU可以自由地使用#其他进程stdout,stderr = await proc.communicate()
该进程将在await asyncio.create_subprocess_exec(...)
完成后立即开始运行。如果在您调用await proc.communicate()
时它还没有完成,它将在那里等待,以便给出您的输出状态。如果它已经完成,proc.communicate()
将立即返回。
这里的要点与Terrels answer类似,但我认为Terrels似乎把事情复杂化了。
有关详细信息,请参阅asyncio.create_subprocess_exec
。
https://stackoverflow.com/questions/636561
复制相似问题