python - 使用 asyncio 在一定时间间隔内运行命令并在之后终止它

标签 python python-asyncio python-os

我正在通过 os.system() 执行 shell 命令。我计划运行它1秒,如果时间超过则终止它。这是我尝试的测试。

import os, time, asyncio

async def cmd():
    os.system("my.py > my.txt") # this processes longer than 1 second

@asyncio.coroutine
def run():
    try:
        yield from asyncio.wait_for(cmd(), 1) # this should excute for more than 1 sec, and hence raise TimeoutError
        print("A")
    except asyncio.TimeoutError:
        os.system("killall python")
        print("B")
    
asyncio.run(run())

但结果始终是“A”,并且txt是由my.py编写的。

我也尝试过:

import os, time, asyncio

async def cmd():
    os.system("my.py > my.txt") # longer than 1 sec

async def run():
    try:
        await asyncio.wait_for(cmd(), 1) # should raise TimeoutError
        print("A")
    except asyncio.TimeoutError:
        os.system("killall python")
        print("B")
    
asyncio.run(run())

产生相同的输出。 代码有什么问题吗?我对 asyncio 很陌生,以前从未使用过它。提前致谢。这很可能不是 wait_for 不会自动停止转换的问题,因为我在第二部分中有一个 killall python 并且事实上, wait_for 函数永远不会引发超时错误,这就是问题所在。

最佳答案

os.system 是一个阻塞操作,因此它不能与 asyncio 很好地配合。每当您使用 asyncio 时,所有“较长”操作都需要异步,否则您将失去使用 asyncio 的所有优势。

import asyncio

async def cmd():
    try:
        proc = await asyncio.create_subprocess_shell(
            "sleep 2 && date > my.txt",
            shell=True,
            stdout=asyncio.subprocess.DEVNULL,
            stderr=asyncio.subprocess.DEVNULL)
        await proc.communicate()

    except asyncio.CancelledError:
        proc.terminate()
        print("X")

async def run():
    try:
        await asyncio.wait_for(cmd(), 1)
        print("A")

    except asyncio.TimeoutError:
        print("B")

asyncio.run(run())

正如 @dim 在评论中提到的,asyncio.create_subprocess_exec 将异步启动外部命令。 wait_for 实际上会引发两个异常:WAITING代码中的 TimeoutError 和等待代码中的 CancelledError 。我们可以使用后者来实现操作被取消,并终止杀死我们的子进程(因为这不会自动完成)。

关于python - 使用 asyncio 在一定时间间隔内运行命令并在之后终止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065010/

相关文章:

python - Try block 捕获错误的异常

python - 如何执行另一个python文件然后关闭现有的文件?

python - 创建自定义管理 View

python - Google 推送部署发布管道被禁用?

python - Asyncio 与 Gevent

python - Python 中的 self 修复任务组

python - 推荐人、被推荐人、 parent 和 child

python - 多维欧拉法python

python - Asyncio 异步运行函数

Python脚本无法找到下载文件夹并打开文件