2012-12-17 5 views
3

나는 ip리스트에서 모든 URL을 추출해야하는데, 이 파이썬 스크립트를 작성했지만 같은 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 
+0

'os'를 한 번 가져 오면 잘됩니다. 두 번 가져올 필요가 없습니다. –

답변

5

threading.Lock를 사용합니다. 잠금은 전역이어야하며 IP 목록을 만들 때 처음에 만듭니다. getIP()

release을의 시작

lock.acquire

당신은 방법을 떠나기 전에.

당신이보고있는 무엇, 스레드 1 value=random.sample를 실행 한 다음 스레드 2 또한 remove에 도달 value=random.sample1 실 전에 실행합니다. 그래서 항목은 스레드 2가 도착할 때 여전히 목록에 있습니다. 따라서 모두 스레드는 동일한 IP를 가져올 수 있습니다.

+2

잠금을 사용하는 더 시원한 방법 : [''with lock : statements''] (http://docs.python.org/2/library/threading.html#using-locks-conditions-and-semaphores-in-the- with 문) (컨텍스트 관리자 (http://docs.python.org/2/reference/datamodel.html#context-managers)를 사용하여 –

+0

def getIP() : \t lock.acquire() \t if LEN (ListaIP) = 0! \t \t 값 = random.sample (ListaIP, 1) 다른 \t \t ListaIP.remove (값 [0]) \t \t 리턴 값 \t : \t \t 인쇄 "\ nListaIPs SA 테 rminat \ n " \t \t sys.exit (1) \t lock.release는() 전역 이름 '잠금' 가 작동하지 정의되어 있지 않습니다 ... 나는 나에게 오류를 제공합니다. – AutoSoft

관련 문제