Python子进程调用效率

Python子进程调用效率,python,subprocess,Python,Subprocess,我正在编写一个python程序,用于ping设备并报告在线/离线状态和延迟。目前,它工作正常,但每当有设备脱机或没有响应时,输出将挂起约5秒 我的问题是,我是否可以独立而不是按顺序ping所有内容,和/或我是否可以在子流程上设置某种时间过滤器,以便在~100-200ms后没有更新内容时,它会转到下一个 下面是我目前正在编写的代码的相关部分 for item in lines: #remove whitespaces, etc from item. hostname = item.rstrip()

我正在编写一个python程序,用于ping设备并报告在线/离线状态和延迟。目前,它工作正常,但每当有设备脱机或没有响应时,输出将挂起约5秒

我的问题是,我是否可以独立而不是按顺序ping所有内容,和/或我是否可以在子流程上设置某种时间过滤器,以便在~100-200ms后没有更新内容时,它会转到下一个

下面是我目前正在编写的代码的相关部分

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
对于行中的项目:
#从项目中删除空格等。
hostname=item.rstrip()
#运行ping并将输出返回到stdout。
#Popen运行cmdline ping,将输出通过管道传输到stdout。read()然后读取该流数据并将其分配给ping_响应变量
ping_response=subprocess.Popen([“ping”,主机名,“-n”,“1]”),stdout=subprocess.PIPE)。stdout.read()
word=“已接收=1”
word2=“无法访问目标主机。”
#用于查找时间值并将其输入列表的正则表达式。
p=重新编译(ur’(?)?
我的问题是,我可以独立地ping所有内容,而不是按顺序ping所有内容吗

当然。这个问题有多种解决方案,包括
线程
多处理
模块

和/或我可以在子流程上设置某种类型的时间过滤器,以便在~100-200毫秒后,如果没有更新,它会转到下一个吗

实际上,您可以使用
-W
选项在
ping
本身(至少在Linux版本)上设置超时:

   -W timeout
          Time to wait for a response, in seconds. The option affects only
          timeout in absence of any responses, otherwise  ping  waits  for
          two RTTs.

Ping
具有超时功能,这将有助于提高脚本的效率

-W waittime
             Time in milliseconds to wait for a reply for each packet sent.  If a reply arrives later, the packet
             is not printed as replied, but considered as replied when calculating statistics.

此外,还有一些其他实用程序可以有效地ping。

这将是一个非常好的多线程应用程序,因为您的程序不受CPU或I/O限制,而是大部分时间都在等待(在网络上或超时)。这将是一个很好的开始。@LukasGraf:here(尽管);
Popen()
创建一个单独的进程并立即返回,而无需等待子进程退出。您不希望1000个线程/进程并行ping 1000个主机。这里可以使用Async.I/O(一个
选择
-like循环,如
twisted
asyncio
gevent
库中使用的循环).related:@J.F.Sebastian“您不希望1000个线程/进程并行ping 1000个主机”-这正是您在
Popen()中所做的
multiple ping script,不是吗?我没有看到任何类型的池。对于线程,您显然会像在另一个示例中一样使用线程池。@LukasGraf:创建100个进程,而不是1000个。如果OP需要同时ping数千个主机,则应考虑(以及)。