假设我有以下 IP 范围 "10.0.0.x"。我需要循环这些 IP 范围内的所有 IP 地址 - "10.0.0.1-255",对每个 IP 地址进行 ping 测试,并检查响应。
以下是我的代码:
以下是我的代码:
for ip in range(1, 256):
fullIP = '10.0.0' + ip
if(Ping(fullIP) == True):
print(fullIP + ' responded')
else:
print(fullIP + ' did not respond')
这段代码是可行的,但很慢。
我想通过多线程使其更加高效,所以我做了以下操作:
def PingRange(start, end):
for ip in range(start, end):
fullIP = '10.0.0' + ip
if(Ping(fullIP) == True):
print(fullIP + ' responded')
else:
print(fullIP + ' did not respond')
try:
thread.start_new_thread( PingRange, (1, 123))
thread.start_new_thread( PingRange, (123, 256))
except:
print "Error: unable to start thread"
这段代码虽然可用,但可以更好地实现更广泛的应用。
如果这段代码被正确编写,那么我不会一直创建两个线程;而是会创建尽可能多的线程,取决于操作系统允许的最大数量。
有些计算机允许8个线程,有些只允许4个,甚至有些不允许线程。
如何在Python中使此程序使用最大数量的线程?