2012-12-17 120 views
3

我需要从一个IP列表中提取所有的URL, 我写了这个python脚本,但我有多次提取相同的IP的问题(使用相同的IP创建更多的线程)。 任何人都可以改进我的解决方案使用多线程?Python多线程

对不起,我的英语 感谢所有

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 
+0

它可以正常导入'os'一次;无需将其导入两次。 –

回答

5

使用threading.Lock。该锁应该是全局的,并在创建IP列表时在开始时创建。

lock.acquiregetIP()

release它开始前你离开的方法。

你看到的是什么,线程1执行value=random.sample,然后线程2还执行value=random.sample以前线程1获取到remove。所以当线程2到达那里时,该项目仍然在列表中。 因此线程有机会获得相同的IP。

+2

使用锁的更酷的方法:[''with lock:statements''](http://docs.python.org/2/library/threading.html#using-locks-conditions-and-semaphores-in-the-用语句)(使用[上下文管理器(http://docs.python.org/2/reference/datamodel.html#context-managers)) –

+0

DEF getIP(): \t lock.acquire() \t如果LEN(ListaIP)= 0: \t \t值= random.sample(ListaIP,1) \t \t ListaIP.remove(值[0]) \t \t返回值 \t否则: \t \t打印“\ nListaIPs SA TE rminat \ n”个 \t \t sys.exit(1) \t lock.release() 全局名称 '锁定' 没有定义 不工作...我给我这个错误。 – AutoSoft