我正在使用Python对某些东西进行基准测试。这可能需要很长时间,因此我想设置一个(全局)超时时间。我使用以下脚本(摘要):
class TimeoutException(Exception):
pass
def timeout_handler(signum, frame):
raise TimeoutException()
# Halt problem after half an hour
signal.alarm(1800)
try:
while solution is None:
guess = guess()
try:
with open(solutionfname, 'wb') as solutionf:
solverprocess = subprocess.Popen(["solver", problemfname], stdout=solutionf)
solverprocess.wait()
finally:
# `solverprocess.poll() == None` instead of try didn't work either
try:
solverprocess.kill()
except:
# Solver process was already dead
pass
except TimeoutException:
pass
# Cancel alarm if it's still active
signal.alarm(0)
但是有时它会产生孤儿进程,但我无法可靠地重现情况。有没有人知道防止这种情况的正确方法?