如果十秒后发生这种情况,我如何打印“进程超时并终止”?
如果没有终止,如何打印“进程成功完成”?
import multiprocessing
import time
def hello():
#process to be terminated after ten seconds
if __name__ == '__main__':
proc = multiprocessing.Process(target=hello)
proc.start()
time.sleep(10)
proc.terminate()
答案 0 :(得分:0)
import time
import multiprocessing
def hello():
#process to be terminated after ten seconds
if __name__ == '__main__':
proc = multiprocessing.Process(target=hello)
proc.start()
time.sleep(5)
if proc.is_alive():
print("Job not finished")
else:
print("Job done")
proc.terminate()
答案 1 :(得分:0)
不是休眠,而是通过超时“加入”进程。如果进程在 10 秒内退出,您将立即收到通知。否则,10 秒后您可以检查退出代码。我在此示例中添加了第三种情况,即非零退出代码的一般故障。
import multiprocessing
import time
def hello():
#process to be terminated after ten seconds
if __name__ == '__main__':
proc = multiprocessing.Process(target=hello)
proc.start()
proc.join(10)
if proc.exitcode is None:
proc.terminate()
proc.join(1)
if proc.exitcode is None:
proc.kill()
print("process timed out and terminated")
elif proc.exitcode == 0:
print("process completed successfully")
else:
print("unexpected error")
有一个窗口,在父母决定一切都出错后,孩子会立即正确退出。如果这是一个问题,你可以做一些更复杂的事情。