2017-05-24 48 views
0

我使用主管来运行这样的脚本。所以当主管停下来或中断时,我试着从脚本中正常退出。这是我当前的代码Python进程池执行程序关闭信号

import concurrent.futures 
import random 
import os 
import signal 
import sys 

executor = concurrent.futures.ProcessPoolExecutor(max_workers=2) 

some_flag = True 

def some_func(): 
    while some_flag: 
     executor.submit(print_some_num) 

def print_some_num(): 
    print("From worker :{}".format(os.getpid())) 
    print(random.randint(0,10)) 

def handler(arg1, arg2): 
    print("Got interrupt") 
    some_flag = False 
    sys.exit("Run for ur life") 
    #executor.shutdown(wait = False) ----> not working 
    print("Shutdown") 

signal.signal(signal.SIGTERM,handler) 
signal.signal(signal.SIGINT,handler) 

if __name__ == '__main__': 
    some_func() 

这工作得很好,现在我很困惑,当我读到executor.shutdown(等待=真/假)。所以我试了一下,我无法让执行器关闭(它只是挂起)。请帮我带着这些疑问

1) what does executor.shutdown do that sys.exit() doesn't do. 
2) What is advisable in production environment? If executor shutdown is required, please help me fix the issue with shutdown. 

回答

0

1)显然,关机停止处理的所有现有的消息,但sys.exit()刚刚出来。 (在文档https://docs.python.org/3/library/concurrent.futures.html

2)如果有人卡在同一个地方,使用一些全局变量来发信号关机。

def some_func(): 
with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor: 
    while True: 
     global some_flag 
     print(some_flag) 
     if not some_flag: 
      executor.shutdown(wait=True) 
      sys.exit() 
     else: 
      executor.submit(print_some_num) 

def print_some_num(): 
    print("From worker :{}".format(os.getpid())) 
    print(random.randint(0,10)) 

def handler(arg1, arg2): 
    global some_flag 
    print("Got interrupt") 
    some_flag = False 
    print("Shutdown") 

signal.signal(signal.SIGTERM,handler) 
signal.signal(signal.SIGINT,handler) 
+0

如果可以做得更好,请添加您的意见。 – Anandan