![](/img/trans.png)
[英]Why do I get NameError: name 'as_completed' is not defined (I have from concurrent.futures import ThreadPoolExecutor)
[英]First time attempting to thread using concurrent.futures-Why do I get no output?
我是python的新手,所以我的代碼可能存在多處錯誤。 但是我無法調試,因為我實際上沒有任何輸出,包括任何錯誤。 希望有幫助。 我在python 3.5中。 干杯!
print('starting')
def simple_function(comic_start, comic_end):
for urlNumber in range(comic_start, comic_end):
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
driver = selenium.webdriver.PhantomJS()
driver.get('http://xkcd.com/%s' % (urlNumber))
print('finding page')
form= driver.title
print(driver.title)
driver.quit()
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(simple_function, (1, 100))
輸出:
runfile('/Users/Seansmac/Desktop/Python/my_classroom/threading_training/concurrent.f1.py', wdir='/Users/Seansmac/Desktop/Python')
starting
編輯:這是與此類似的問, Concurrent.futures使用指南-一個同時使用線程和處理的簡單示例 ,但是就像OP所說的那樣,答案太復雜了!
您正在將具有兩個值的元組映射到該函數。 在每個映射上,它只發送一個參數,但是您的函數需要兩個論點comic_start
和comic_end
要看到這一點,您可以排除其他爭論並執行以下操作:
def simple_function(first_arg):
print(first_arg)
with cf.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(simple_function, (1, 100))
結果:
1
100
修改后的代碼:
import concurrent.futures as cf
def simple_function(_range):
#fill with driver stuff etc
for num in _range:
print('Downloading page http://xkcd.com/%s...' % (num))
_max = 200 #max range you want
workers = 10
with cf.ThreadPoolExecutor(max_workers=workers) as e:
cs= _max // workers #chunksize to split across threads
#we chunk the range to be split across the threads so you can iterate
#over the chunked range in the mapped function.
#x + cs if x + cs <= _max else _max next upper bound by chunksize but
#we don't want to exceed the maximum range you want, so we default to _max
#if the next upper bound exceeds this
#x - 1 if x!= 0 else x, start initial range at 0, and last upper
#bound is exclusive so x - 1 if were not at the initial range.
ranges = [range(x - 1 if x != 0 else x, x + cs if x + cs <= _max else _max)
for x in range(0, _max, cs)]
e.map(simple_function, ranges)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.