【发布时间】:2015-07-18 13:28:37
【问题描述】:
我正在编写一个 python 程序,它可以 ping 设备并报告在线/离线状态和延迟。现在它工作正常,但只要有设备离线或没有响应,输出就会挂起大约 5 秒钟。
我的问题是我是否可以独立而不是按顺序 ping 所有内容和/或我可以在子进程上设置某种时间过滤器,这样,如果在 ~100-200 毫秒后没有更新,它会转到下一个?
这是我目前正在处理的代码的相关部分
for item in lines:
#remove whitespaces, etc from item.
hostname = item.rstrip()
#Run ping and return output to stdout.
#subprocess.Popen runs cmdline ping, pipes the output to stdout. .stdout.read() then reads that stream data and assigns it to the ping_response variable
ping_response = subprocess.Popen(["ping", hostname, "-n", '1'], stdout=subprocess.PIPE).stdout.read()
word = "Received = 1"
word2 = "Destination host unreachable."
#Regex for finding the time values and inputting them in to a list.
p = re.compile(ur'(?<=time[<=])\S+')
x = re.findall(p, ping_response)
if word2 in ping_response:
print "Destination Unreachable"
elif word in ping_response:
print "%s is online with latency of " % hostname +x[0]
else:
print "%s is offlineOffline" % hostname
【问题讨论】:
-
这将是一个非常好的多线程应用程序,因为您的程序不受 CPU 或 I/O 限制,而是大部分时间都在等待(在网络上或超时)。 Doug Hellmann's article on the
threadingmodule 将是一个不错的起点。 -
@LukasGraf: You don't need threads 在这里(尽管they can be used);
Popen()创建一个单独的进程并立即返回,而无需等待子进程退出。您不希望 1000 个线程/进程并行 ping 1000 个主机。异步。可以在这里使用 I/O(类似select的循环,例如在twisted、asyncio、gevent库中使用)。 -
@JFSebastian “您不希望 1000 个线程/进程并行 ping 1000 台主机” - 这正是您在
Popen()多个 ping 中所做的脚本,不是吗?我看不到那里有任何形式的汇集。对于线程,您显然会像在其他示例中那样使用线程池。 -
@LukasGraf: the script 创建 100 个进程,而不是 1000 个。如果 OP 需要同时 ping 数千个主机,则应考虑 async. io(以及 thread pooling)。
标签: python subprocess