0
멀티 스레딩을 사용하여 무한 루프 (지연 후 몇 초 후 데이터 확인) 기능을 실행하려고합니다. CSV 파일에서 데이터를 읽었으므로 Queues도 사용하고 있습니다.멀티 스레딩 및 큐를 사용하는 동안 무한 루프가 자동으로 종료됩니다.
멀티 쓰레딩/큐를 사용하지 않을 때 현재 사용하는 함수가 좋지만 사용할 때 함수는 한 번만 반복 된 다음 중지됩니다.
여기 내 기능에는 무한 루프가 있습니다. 첫 번째 True 루프는 스레드에 대한 것입니다 (CSV에있는 행보다 적은 수의 스레드를 사용하는 경우를 대비하여) 함수는 True 루프 동안 두 번째 만 필요합니다.
def doWork(q):
while True:
#logging.info('Thread Started')
row=q.get()
url = row[0]
target_price = row[1]
#logging.info('line 79')
while True:
delay=randint(5,10)
headers = {'User-Agent': generate_user_agent()}
print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')+': '+'Sleeping for ' + str(delay) + ' seconds'
#logging.info('line 81')
eventlet.sleep(delay)
try:
#logging.info('line 85')
with requests.Session() as s:
#logging.info('line 87')
with eventlet.Timeout(10, False):
page = s.get(url,headers=headers,proxies=proxyDict,verify=False)
#logging.info('line 89')
tree = html.fromstring(page.content)
#logging.info('line 91')
price = tree.xpath('//div[@class="a-row a-spacing-mini olpOffer"]/div[@class="a-column a-span2 olpPriceColumn"]/span[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]/text()')[0]
title = tree.xpath('//h1/text()')[0]
#logging.info('line 93')
new_price = re.findall("[-+]?\d+[\.]?\d+[eE]?[-+]?\d*", price)[0]
#logging.info('line 95')
old_price = new_price
#logging.info('line 97')
#print price
print new_price
print title + 'Current price:' + new_price
if float(new_price)<float(target_price):
print 'Lower price found!'
mydriver = webdriver.Chrome()
send_simple_message()
login(mydriver)
print 'Old Price: ' + old_price
print 'New Price: ' + new_price
else:
print 'Trying again'
q.task_done()
except Exception as e:
print e
print 'Error!'
q.task_done()
여기 내 스레드 드라이버 기능입니다.
q = Queue(concurrent * 2)
if __name__ == "__main__":
for i in range(concurrent):
t = Thread(target=doWork,args=(q,))
t.daemon = True
t.start()
try:
with open('products.csv','r') as f:
reader = csv.reader(f.read().splitlines())
for row in reader:
q.put((row[0],row[1]))
q.join()
except KeyboardInterrupt:
sys.exit(1)
죄송합니다. q.join()이 아닌 q.task_done()을 의미했습니다. –