Aut*_*oft 3 python multithreading
我需要从ip列表中提取所有url,我写了这个python脚本,但我有多次提取相同的ip的问题(使用相同的ip创建更多的线程).任何人都可以使用多线程改进我的解决方案吗?
对不起我的英语谢谢大家
import urllib2, os, re, sys, os, time, httplib, thread, argparse, random
try:
ListaIP = open(sys.argv[1], "r").readlines()
except(IOError):
print "Error: Check your IP list path\n"
sys.exit(1)
def getIP():
if len(ListaIP) != 0:
value = random.sample(ListaIP, 1)
ListaIP.remove(value[0])
return value
else:
print "\nListaIPs sa terminat\n"
sys.exit(1)
def extractURL(ip):
print ip + '\n'
page = urllib2.urlopen('http://sameip.org/ip/' + ip)
html = page.read()
links = re.findall(r'href=[\'"]?([^\'" >]+)', html)
outfile = open('2.log', 'a')
outfile.write("\n".join(links))
outfile.close()
def start():
while True:
if len(ListaIP) != 0:
test = getIP()
IP = ''.join(test).replace('\n', '')
extractURL(IP)
else:
break
for x in range(0, 10):
thread.start_new_thread( start, () )
while 1:
pass
Run Code Online (Sandbox Code Playgroud)
用一个threading.Lock.锁应该是全局的,并在创建IP列表时在开头创建.
lock.acquire 在开始时 getIP()
并且release在你离开方法之前.
你看到的是,线程1执行value=random.sample,然后线程2也在线程1到达value=random.sample 之前执行remove.所以当线程2到达那里时,该项仍然在列表中.因此,两个线程都有机会获得相同的IP.