退出Python3线程池中无限循环的安全方法

2024-09-30 16:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python3模块:

  • requests对于HTTP GET调用几个粒子光子,这些粒子光子被设置为简单的HTTP服务器

  • 作为一个客户端,我使用Raspberry Pi(它也是一个访问点)作为一个HTTP客户机,它使用multiprocessing.dummy.Pool对上述光子进行HTTP GET响应

轮询程序如下:

def pollURL(url_of_photon):
    """
    pollURL: Obtain the IP Address and create a URL for HTTP GET Request
    @param: url_of_photon: IP address of the Photon connected to A.P.
    """
    create_request = 'http://' + url_of_photon + ':80'
    while True:
        try:
            time.sleep(0.1) # poll every 100ms
            response = requests.get(create_request)
            if response.status_code == 200:
                # if success then dump the data into a temp dump file
                with open('temp_data_dump', 'a+') as jFile:
                    json.dump(response.json(), jFile)
            else:
               # Currently just break
               break
        except keyboardInterrupt as e:
            print('KeyboardInterrupt detected ', e)
            break

url_of_photon值是从Pi上的dnsmasq.leases文件获得的简单的IPv4地址。在

main()函数:

^{pr2}$

问题

程序运行良好,但是当我按下CTRL+C时,程序不会终止。经过挖掘,我发现这样做的方法是使用CTRL+\

我如何在我的pollURL函数中使用它来安全地退出程序,即执行poll.join(),这样就没有剩下的进程了?在

注意事项

函数永远无法识别KeyboardInterrupt。因此,我在尝试检测CTRL+\时遇到了麻烦。在


Tags: ofthe函数程序httpurlgetresponse
1条回答
网友
1楼 · 发布于 2024-09-30 16:32:58

pollURL在另一个线程中执行。在Python中,信号只在主线程中处理。因此,SIGINT只在主线程中引发键盘中断。在

signal documentation

Signals and threads

Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.

Besides, only the main thread is allowed to set a new signal handler.

您可以用以下方式实现您的解决方案(伪代码)。在

event = threading.Event()

def looping_function( ... ):
    while event.is_set():
        do_your_stuff()

def main():
    try:
        event.set()
        pool = ThreadPool()
        pool.map( ... )
    except KeyboardInterrupt:
        event.clear()
    finally:
        pool.close()
        pool.join()

相关问题 更多 >