一次运行多个.exe文件python

时间:2014-02-05 20:54:11

标签: python python-2.7 ping lan

如何在Python中一次运行多个.exe文件?我改编了另一个堆栈溢出问题的代码来制作局域网pinger。此pinger必须ping子网掩码内的所有设备,因此在我的情况下,它必须运行ping.exe 255次。因此,运行它需要很长时间。如何一次多次运行ping.exe?

我目前使用的代码如下:

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        print "SCANNING YOUR LAN..."
        for n in xrange(1, 256):
                ip="192.168.0.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        pass
                else:
                        print ip, "is active"

如何提高此计划的效率?

2 个答案:

答案 0 :(得分:2)

请勿将wait放入Popen来电。

如果你需要它们并行运行,但是想要在完成之前等待它们全部完成,请执行:

# Create a list of the running processes
running = [subprocess.Popen(...) for ip in ips]
# Wait /after/ all process have launched. 
[process.wait() for process in running]
# Rest of code here.

当然,您必须重新制定一些内容以制作ips列表等。

答案 1 :(得分:1)

如果您有一个名为“ipaddress.txt”的文件,其中包含所有IP,您可以像我想象的那样:

    f = open('ipaddress.txt')
    lines = f.readlines()
    f.close()
    for line in lines:
        subprocess.Popen(["ping", "-a", "-n", "l"]

即使该代码不起作用,它仍然应该是概念。您需要ping 192.168.0.1/255,并将活动的ips显示给您。

相关问题