我正在使用 python3 模块:
-
requests
对于 http get 调用几个粒子光子,这些光子以简单 HTTP服务器设置为 -
作为客户端,我正在使用raspberry pi(也是访问点)作为 http client 使用
multiprocessing.dummy.Pool
来制作 http get resquests to resquests上述光子
轮询程序如下:
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
值很简单 IPv4地址从PI上可用的dnsmasq.leases
文件中获得。
main()
功能:
def main():
# obtain the IP and MAC addresses from the Lease file
IP_addresses = []
MAC_addresses = []
with open('/var/lib/misc/dnsmasq.leases', 'r') as leases_file:
# split lines and words to obtain the useful stuff.
for lines in leases_file:
fields = lines.strip().split()
# use logging in future
print('Photon with MAC: %s has IP address: %s' %(fields[1],fields[2]))
IP_addresses.append(fields[2])
MAC_addresses.append(fields[1])
# Create Thread Pool
pool = ThreadPool(len(IP_addresses))
results = pool.map(pollURL, IP_addresses)
pool.close()
pool.join()
if __name__ == '__main__':
main()
问题
程序运行良好,但是当我按 ctrl c 时,程序不会终止。挖掘后,我发现这样做的方法是使用 ctrl
我如何在pollURL
函数中使用它以安全地退出程序,即执行poll.join()
,因此没有剩余的过程?
注释:
KeyboardInterrupt
从未通过该功能识别。因此,我面临着尝试检测 ctrl 。
pollURL
在另一个线程中执行。在Python中,仅在主线程中处理信号。因此,SIGINT仅在主线程中提高键盘干扰。
来自信号文档:
信号和线程
Python信号处理程序始终在主Python线程中执行,即使在另一个线程中接收了信号。这意味着信号不能用作线际间通信的一种手段。您可以使用螺纹模块的同步原始图。
此外,仅允许主线程设置一个新的信号处理程序。
您可以以以下方式实现解决方案(伪代码)。
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()