Python Subprocess Timeout Guide
In Python, you can set a timeout using the subprocess.run() function. Introduced in Python 3.5, subprocess.run() makes it easy to execute external commands and wait for them to finish.
Here is an example code for setting a timeout.
import subprocess
# 执行命令,并设置超时时间为5秒
try:
result = subprocess.run(['command', 'arg1', 'arg2'], timeout=5, check=True)
# 如果命令成功执行,可以通过result的属性获取命令的输出、返回码等信息
print('命令输出:', result.stdout)
print('返回码:', result.returncode)
except subprocess.TimeoutExpired:
# 如果超时,可以在这里处理超时情况
print('命令执行超时')
except subprocess.CalledProcessError as e:
# 如果命令执行失败,可以在这里处理失败情况
print('命令执行失败:', e.returncode, e.output)
In the example code above, the timeout parameter of the subprocess.run() function is used to set the time limit in seconds. If the command is not completed within the specified timeout, a subprocess.TimeoutExpired exception will be raised.