![](/img/trans.png)
[英]Using Tkinter With Concurrent.Futures / ThreadPoolExecutor Class
[英]Create progress Bar using concurrent.futures in ThreadPoolexecutor process
我有一個 python 腳本,它連接到多個遠程主機並執行 linux 命令來獲取信息。 今天的主機數量約為 400 台主機,在這種情況下,我使用 ThreadPoolExecutor 在盡可能短的時間內完成所有任務。
一切正常,我在 100 秒左右獲得所有數據。 問題是我不知道這段時間內進程的 state 怎么樣,我想添加一個進度條,當所有線程結束時結束。
在我身邊,我添加了新代碼,使這個進度條成為我的腳本,使用睡眠時間,但正如我所見,進度條沒有與線程進程同步(進度條在線程進程前幾秒結束)。
有更好的解決方案嗎? 當所有這些工作正常時,我想將此進度條遷移到 Django 網站。
在這里,您有我的代碼腳本的一部分。
for host in lista_hosts:
res_versiones[host] = val_defecto
# print(res_versiones)
LENGTH = len(lista_hosts) # Number of iterations required to fill pbar
pbar = tqdm(total=LENGTH, desc='consulta_comando') # Init pbar
with ThreadPoolExecutor(200) as executor:
for host in lista_hosts:
host_dns = add_dns_cc.add_dns_concesion(host)
res_command_remote = executor.submit(comando_remoto.comando_remoto_hosts, host_dns, comando, res_versiones, user, clave_rsa, passwd)
time.sleep(0.2)
pbar.update(n=1) # Increments counter
end = time.time() print(f"Runtime of the program is {end - start}")
謝謝
每次將作業提交給Executor
時,您的代碼都會更新進度條,但每次作業完成時都應該更新它。
您可以將submit
返回的期貨保存在列表中,並使用as_completed
檢查是否完成:
from concurrent.futures import ThreadPoolExecutor, as_completed
# ... snip.....
LENGTH = len(lista_hosts) # Number of iterations required to fill pbar
pbar = tqdm(total=LENGTH, desc='consulta_comando') # Init pbar
with ThreadPoolExecutor(200) as executor:
futures = [executor.submit(comando_remoto.comando_remoto_hosts,
add_dns_cc.add_dns_concesion(host),
comando, res_versiones, user, clave_rsa,
passwd) for host in lista_hosts]
for _ in as_completed(futures):
pbar.update(n=1) # Increments counter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.