【问题标题】:Python subprocess call efficiencyPython子进程调用效率
【发布时间】: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 threading module 将是一个不错的起点。
  • @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


【解决方案1】:

我的问题是我可以单独 ping 一切而不是按顺序

当然。这个问题有多种解决方案,包括threading 和multiprocessing 模块。

和/或我是否可以在子进程上设置某种时间过滤器,以便如果在 ~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.

【讨论】:

    【解决方案2】:

    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.
    

    另外,here 是其他一些可以有效 ping 的实用程序。

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多