Instead of using os.system
, try subprocess.run
and use the timeout
option:
# file: sleepy.py
import time
time.sleep(10)
# file: monitor.py
import subprocess
import shlex
try:
subprocess.run(shlex.split("python sleepy.py"), timeout=5)
except subprocess.TimeoutExpired:
print("Timed out")
When you run python monitor.py
, it blocks until the timeout is reached.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…