我一直在尝试做一个小的python程序来监控和返回来自不同服务器的ping结果。我已经到了point序列中的每个设备都变得低效和缺乏性能的地步。我想在我的python上同时连续ping我的每个目标。
对此最好的方法是什么?耽误您时间,实在对不起
def get_latency(ip_address, port):
from tcp_latency import measure_latency
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
latency = str(measure_latency(host=ip_address, port=port, runs=1, timeout=1))[1:-1]
#add to table and upload to database function()
ip_address_list = [('google.com', '80'), ('bing.com', '80')]
#Problem
#run function simultaneously but with different arguments
get_latency(ip_address_list[0][0], ip_address_list[0][1])
get_latency(ip_address_list[1][0], ip_address_list[1][1])发布于 2020-01-18 22:34:16
For循环不能同时运行。
您可以使用线程来同时运行。
请看以下内容:
import threading
def get_latency(ip_address, port):
from tcp_latency import measure_latency
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
latency = str(measure_latency(host=ip_address, port=port, runs=1, timeout=1))[1:-1]
#add to table and upload to database function()
ip_address_list = [('google.com', '80'), ('bing.com', '80')]
#adding to thread
t1 = threading.Thread(target=get_latency, args=(ip_address_list[0][0], ip_address_list[0][1]))
t2 = threading.Thread(target=get_latency, args=(ip_address_list[1][0], ip_address_list[1][1]))
# starting thread
t1.start()
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!") 发布于 2020-01-18 22:19:16
您可以使用for循环来实现此目的。如下所示:
for i in range(len(ip_address_list)):
print(get_latency(ip_address_list[i][0], ip_address_list[i][1]))此外,还应在编写函数之前定义模块并返回结果
from tcp_latency import measure_latency
from datetime import datetime
def get_latency(ip_address, port):
.
.
.
return resultshttps://stackoverflow.com/questions/59801340
复制相似问题