我正在编写一个程序,该程序不断检查某些IP地址是否连接到网络。如果是,什么也不会发生。如果它们在一段时间内没有连接,则会触发一个操作。据我所知,我的脚本可以按预期工作,但当我尝试使用ctrl+c
退出它时,它根本不会停止。我想这和我使用的线程有关,但我不知道它到底是什么。这是我迄今为止的代码:
import os
import time
from threading import Timer, Thread
import json
with open("ip_adresses.json", "r") as f:
ip_adresses_dict = json.load(f)
def timeout():
print("ACTION IS TRIGGERED")
# dummy Timer thread
print("dummy timer created")
t = Timer(999999999, timeout)
t.daemon = True
try:
while True:
ip_adress_reachable = []
for key, value in ip_adresses_dict.items():
if os.system(f"ping -c 1 -W 1 {value} > /dev/null") is 0: # this means its reachable
ip_adress_reachable.append(True)
else:
ip_adress_reachable.append(False)
print(ip_adress_reachable)
# if no ip adresses are reachable and no timer running, start a timer.
if any(ip_adress_reachable) == False and t.is_alive() == False:
print("starting a new thread")
t = Timer(15, timeout)
t.daemon = True
t.start()
# If in the meantime ip adress gets reachable cancel the timer.
elif any(ip_adress_reachable) == True and t.is_alive() == True:
# cancel the timer
print("timer was canceled")
t.cancel()
except KeyboardInterrupt:
print("quitting")
t.join(1)
我有点迷路了,因为我认为deamon
线程会在主循环完成后(即在我按下ctr+c
后(停止
如果有人能帮我,我将不胜感激。
经过测试,我发现所有的问题都使os.system()
捕获Ctrl+C
以停止进程在os.system()
-ping
-中运行,并且它没有将这些信息发送到Python。
如果运行ping
的时间更长,则跳过/dev/null
os.system(f"ping -c 5 -W 1 {value}")
然后你会看到Ctrl+C
停止ping
如果我使用subprocess
,那么我就没有这个问题。
subprocess.call(f"ping -c 1 -W 1 {value} > /dev/null", shell=True)
我在Linux Mint 20上测试的代码(基于Ubuntu 20.04(
#import os
import time
from threading import Timer, Thread
#import json
import subprocess
#with open("ip_adresses.json", "r") as f:
# ip_adresses_dict = json.load(f)
ip_adresses_dict = {
'x': '192.168.0.1',
'y': '192.168.0.2',
'z': '192.168.0.3',
}
def timeout():
print("ACTION IS TRIGGERED")
# dummy Timer thread
print("dummy timer created")
t = Timer(999999999, timeout)
t.daemon = True
try:
while True:
ip_adress_reachable = []
for key, value in ip_adresses_dict.items():
print('[DEBUG] start process')
#result = os.system(f"ping -c 1 -W 1 {value} > /dev/null")
#result = os.system(f"ping -c 5 -W 1 {value}")
result = subprocess.call(f"ping -c 1 -W 1 {value} > /dev/null", shell=True)
print('[DEBUG] end process')
ip_adress_reachable.append( result == 0 )
print(ip_adress_reachable)
# if no ip adresses are reachable and no timer running, start a timer.
if any(ip_adress_reachable) is False and t.is_alive() is False:
print("starting a new thread")
t = Timer(15, timeout)
t.daemon = True
t.start()
# If in the meantime ip adress gets reachable cancel the timer.
elif any(ip_adress_reachable) is True and t.is_alive() is True:
# cancel the timer
print("timer was canceled")
t.cancel()
except KeyboardInterrupt:
print("quitting")
if t.is_alive():
t.join(1)
文档:替换操作系统((