我想做一个能ping远程IP的控制台程序。我使用多线程同时ping多个IP。当所有IP都可达时,所有IP看起来都很棒,但当一个IP不可达时,其他线程必须等待很长时间,直到坏的ping完成(我特意选择了一个无法ping通的IP),这是由于join方法,它会一直等到所有线程结束。当我刚刚删除join方法时,我的PC崩溃了。
我做了以下工作来克服这个问题(创建了无限的ping函数,这样就不会因为里面的无限方法而导致thead结束),并在代码中保留联合方法,它工作正常,但还有更好的选择吗?我猜这个解决方案在消耗资源或其他方面可能会有一些缺点。
我的工作代码,我对此有疑问:
下面方法在t100时间间隔内对b (IP)执行一次ping操作
def do_ping(b,t100):
a=os.system(f"ping -n 1 {b}")
h=good_time(time.localtime(),1)
with open(f"noob_{h}_{b}.txt",mode="a") as f:
t=good_time(time.localtime(),0)
if(a==int(0)):
f.write(f"The remote destination {b} is reachable, everyting is enter code hereOKAY. {t} \n")
elif(a==int(1)):
f.write(f"Ping {b} failed! {t} \n")
time.sleep(int(t100))一个IP地址的无限ping:
def ping1(b,t100):
while(True):
IP_Op.do_ping(b,t100)主程序:
while(True):
treadsN=[]
for i in b:b是一个is列表(整个程序也会将结果写入文件,如果ping长时间失败,将来会发送电子邮件
treadsN.append(threading.Thread(target=IP_Op.ping1, args=(i,3)))
for i in treadsN:
i.start()
for i in treadsN:
i.join()发布于 2018-09-04 01:35:34
你不需要线程来执行多个进程-只要使用subprocess.Popen -它不会像os.system那样阻塞,所以你可以多次运行它,它们都会并行运行。
如果b是一个包含所有ips的列表:
import subprocess
while True:
result = []
for ip in b:
p = subprocess.Popen(['ping', '-n', '1', ip]) # runs ping in background
result.append(p) # store the Popen object for later result retrieval这将在后台运行多个ping进程!现在,您只需解析结果:
try_again = []
for ip, p in zip(b, result):
if p.wait() == 0:
print(ip, 'is ok!')
else:
print(ip, 'failed!')
try_again.append(ip)然后,如果需要,您可以重复失败的操作:
if not try_again:
break
time.sleep(100)
b = try_againhttps://stackoverflow.com/questions/52153912
复制相似问题