我正在通过 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/