I'm excuting a shell command by os.system()
. I planned to run it for 1 second, then terminate it if time exceeded. Here's what I tried instead as a test.
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())
But the result was always "A" and the txt was written by my.py.
I also tried:
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())
results in the same output.
What's wrong with the code? I'm pretty new to asyncio and never used it before. Thanks in advance. It's most likely not the problem that wait_for
does not stop the cast automatically, since I have a killall python
in the second part and in fact, the wait_for function never raises the timeout error, that's the problem.