2014-02-11 4 views
1

저는 파이썬을 처음 사용하고 있으며 파일의 각 줄을 get_result 함수에 전달하는 아래 스레드 된 스크립트를 작성했습니다. 내가 대기열 및 스레딩을 사용Python 스레딩 - 예기치 않은 출력

import requests 
import Queue 
import threading 
import re 
import time 

start_time = int(time.time()) 
regex_to_use = re.compile(r"^") 


def get_result(q, partial_url): 
    partial_url = regex_to_use.sub("%s" % "http://www.domain.com/", partial_url) 
    r = requests.get(partial_url) 
    status = r.status_code 
    #result = "nothing" 
    if status == 200 or status == 301: 
     result = str(status) + " " + partial_url 
     print(result) 


#need list of urls from file 
file_list = [line.strip() for line in open('/home/shares/inbound/seo/feb-404s/list.csv', 'r')] 
q = Queue.Queue() 
for url in file_list: 
    #for each partial. send to the processing function get_result 
    t = threading.Thread(target=get_result, args=(q, url)) 
    t.start() 

end_time = int(time.time()) 
exec_time = end_time - start_time 
print("execution time was " + str(exec_time)) 

,하지만 일어나고있는 것은의 인쇄 것입니다 다음 get_result 기능은해야 출력은 URL 및 상태 코드는 코드는 200 (301)

를 다음있다가되어있는 경우로 "execution time was x"가 출력되고 있습니다. 전에 스레드가 데이터 출력을 완료했습니다.

e.e.

200 www.domain.com/ok-url 
200 www.domain.com/ok-url-1 
200 www.domain.com/ok-url-2 
execution time was 3 
200 www.domain.com/ok-url-4 
200 www.domain.com/ok-ur-5 
200 www.domain.com/ok-url-6 

어떻게 이런 일이, 그리고 내가 스크립트의 끝에서 스크립트 실행 쇼, 즉 한 번에 모든 URL 처리 및 출력 된있을 수 있습니다 어떻게 알고 싶습니다 : 일반적인 출력은?

utdemir이 제공 한 답변 덕분에 다음과 같은 코드가 업데이트되었습니다.

import requests 
import Queue 
import threading 
import re 
import time 

start_time = int(time.time()) 
regex_to_use = re.compile(r"^") 


def get_result(q, partial_url): 
    partial_url = regex_to_use.sub("%s" % "http://www.domain.com/", partial_url) 
    r = requests.get(partial_url) 
    status = r.status_code 
    #result = "nothing" 
    if status == 200 or status == 301: 
     result = str(status) + " " + partial_url 
     print(result) 


#need list of urls from file 
file_list = [line.strip() for line in open('/home/shares/inbound/seo/feb-404s/list.csv', 'r')] 
q = Queue.Queue() 
threads_list = [] 

for url in file_list: 
    #for each partial. send to the processing function get_result 
    t = threading.Thread(target=get_result, args=(q, url)) 
    threads_list.append(t) 
    t.start() 

for thread in threads_list: 
    thread.join() 


end_time = int(time.time()) 
exec_time = end_time - start_time 
print("execution time was " + str(exec_time)) 
+0

당신은 스레드를 시작하고 실행을 계속합니다. 당신은 그들이 끝내기를 기다리지 않으므로, (적어도 그들 중 일부는) 끝나기 전에 "execution time was X"라고 인쇄합니다. 스레드가 끝날 때까지 기다리려면 thread.join() –

답변

3

기다리는 스레드는 join이어야합니다. 그렇지 않으면 백그라운드에서 계속 실행됩니다. 이처럼

:

threads = [] 
for url in file_list: 
    ... 
    threads.append(t) 

for thread in threads: 
    thread.join() # Wait until each thread terminates 

end_time = int(time.time() 
... 
+0

대단히 감사합니다. 위에서 새 코드를 게시하고 답변으로 표시합니다. – pokero