Python多线程
我需要从ip列表中提取所有URL, 我编写了这个python脚本,但是我多次提取相同的ip时遇到了问题(使用相同的ip创建了更多线程)。 有人能改进我使用多线程的解决方案吗 对不起,我的英语不好 谢谢大家Python多线程,python,multithreading,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):
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
使用
线程。锁定。锁应该是全局的,并在创建IP列表的开始处创建
锁定。在getIP()的开始处获取
然后在离开方法之前释放它
您看到的是,线程1执行value=random.sample
,然后线程2在线程1到达remove
之前也执行value=random.sample
。因此,当线程2到达那里时,该项仍然在列表中。
因此,两个线程都有可能获得相同的IP。使用锁的方法:(使用)def getIP():lock.acquire()(如果len(ListaIP)!=0:value=random.sample(ListaIP,1)ListaIP.remove(值[0])返回值else:print“\nListaIPs sa Terminate\n”sys.exit(1)lock.release()未定义全局名称“lock”无效。。。我告诉我这个错误。导入os
一次就可以了;不需要导入两次。