【发布时间】:2023-04-01 14:38:01
【问题描述】:
我使用 multiprocessing 包来运行函数:run_performance,它会在其中加载包含多个 csv 文件的 zip 文件。
我搜索以正确显示进度条,其中包含每个 zip 文件中的 csv 数量。 使用我的代码,显示不连贯/错误:
我的代码:
from alive_progress import alive_bar
from zipfile import ZipFile
import os
def get_filepaths(directory):
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
def count_files_7z(myarchive):
cnt_files = []
with closing(ZipFile(myarchive)) as archive:
for csv in archive.namelist():
cnt_files.append(csv)
return cnt_files
def run_performance(zipobj):
zf = zipfile.ZipFile(zipobj)
cnt = count_files_7z(zipobj)
with alive_bar(len(cnt)) as bar:
for f in zf.namelist():
bar()
with zf.open(f) as myfile:
print(myfile) # and done other things
list_dir = "path_of_zipfiles" #
for idx1, folder in enumerate(list_dir):
get_all_zips = get_filepaths(folder)
for idx2, zip_file in enumerate(get_all_zips):
with zipfile.ZipFile(zip_file) as zipobj:
p = Process(target=run_performance,args=(zipobj.filename,))
p.start()
p.join()
我的展示:
|████▌ | ▄▆█ 1/9 [11%] in 0s (3.3/s, eta: 0s)|████▌ | ▄▆█ 1/9 [11%] in 0s (3.3/s, eta: 0s)|████▌ | ▄▆█ 1/9 [11%] in 0s (3.3/s, eta: 0s
...
如果我将p.join() 行与p.start() 放在相同的缩进处,则显示正确,但多处理不再起作用。
所以脚本花费了太多时间:
1 分 18 秒与 0 分 14 秒
期望的输出:
|████████████████████████████████████████| 1/1 [100%] in 2.4s (0.41/s)
|████████████████████████████████████████| 2/2 [100%] in 4.7s (0.43/s)
|████████████████████ | ▄▂▂ 1/2 [50%] in 2s (0.6/s, eta: 0s)
【问题讨论】:
-
如果您想同时运行多个进程,我建议您使用
multiprocessing.Pool并调用Pool.join(),而不是单独加入任何进程。 -
我想我知道会发生什么。请在`p.start()`前加上
print()。 -
请找到:[root@vm-grafana bin]# time ./02-pickle-client.py 一些空格.. 正在加载 csv 文件 |████████████ ████████| 2/2 [100%] in 0.8s (2.41/s) 加载 csv 文件 |████████████████████| 1/1 [100%] in 0.9s (1.09/s) 加载 csv 文件 |████████████████████| 2.1 秒内 2/2 [100%] (0.96/s)
-
但是显示应该会更好,只是因为打印了很多空间.. 什么附加?
标签: python multiprocessing progress-bar