我有一个服务器,我想在一个单独的进程中运行并处理KeyBoardInterrupt
异常以阻止它:
import multiprocessing as mp
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
def server_spawner():
server = HTTPServer(('', 12345), BaseHTTPRequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.shutdown()
server.server_close()
if __name__ == '__main__':
server_proc = mp.Process(target=server_spawner)
server_proc.start()
server_proc.join()
但是当我按下CTRL+C
时,我会得到这样的追溯:
^CTraceback (most recent call last):
File "data_miner.py", line 60, in <module>
server_proc.join()
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 145, in join
res = self._popen.wait(timeout)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/forking.py", line 154, in wait
return self.poll(0)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/forking.py", line 135, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
如何正确处理KeyBoardInterrupt
并加入多进程程序中的进程?
答案 0 :(得分:0)
来自Jesse Noller的博客。
import multiprocessing as mp
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
def server_spawner():
server = HTTPServer(('', 12345), BaseHTTPRequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.shutdown()
server.server_close()
if __name__ == '__main__':
server_proc = mp.Process(target=server_spawner)
server_proc.start()
try:
server_proc.join()
except KeyboardInterrupt:
server_proc.terminate()
server_proc.join()