python - 使用不同的参数同时运行相同的函数

标签 python python-3.x

我一直在尝试制作一个小型 python 程序来监视并返回来自不同服务器的 ping 结果。我已经达到了这样一个地步:对序列中的每个设备进行 ping 操作变得效率低下且缺乏性能。我想在我的 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])

最佳答案

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!") 

关于python - 使用不同的参数同时运行相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801340/

相关文章:

python - 如何删除以用户选择的字母开头的所有项目?

python-3.x - 给定一个节点,烧毁整个二叉树需要多长时间?

python - 使用reduce函数减少python中的大数据集

python - 如何打印到 .txt

python - SublimeREPL 到 python

python - 如何使用Python通过mechanize实现网页抓取后的结果缓存

python - 递归帕斯卡三角形布局

python-3.x - 如何使用超时停止阻塞函数 subscribe.simple

python - 将字符编码映射到每个字符的最大字节数

python - 将命令提示符输出重定向到 python 生成的窗口