Skip to main content
 首页 » 编程设计

python之如何更改进度条的位置之多处理

2025年02月15日8zhujiabin

首先,我是 Python 新手。这与问题无关,但我不得不提一下。

我正在创建一个爬虫作为我的第一个项目,以了解 Python 中的工作原理,但到目前为止这是我的主要问题......在使用 requests 时了解终端中的“如何获得多个进度条”和 pathos.multiprocessing .

我设法完成了所有事情,我只是想获得更漂亮的输出,所以我决定添加进度条。我正在使用 tqdm因为我喜欢它的外观,而且它似乎最容易实现。

这是我的方法,目的是下载文件。

def download_lesson(self, lesson_data): 
    if not 'file' in lesson_data: 
        return print('=> Skipping... File {file_name} already exists.'.format(file_name=lesson_data['title'])) 
 
    response = requests.get(lesson_data['video_source'], stream=True) 
    chunk_size = 1024 
 
    with open(lesson_data['file'], 'wb') as file: 
        progress = tqdm( 
            total=int(response.headers['Content-Length']), 
            unit='B', 
            unit_scale=True 
        ) 
 
        for chunk in response.iter_content(chunk_size=chunk_size): 
            if chunk: 
                progress.update(len(chunk)) 
                file.write(chunk) 
 
        progress.close() 
        print('=> Success... File "{file_name}" has been downloaded.'.format(file_name=lesson_data['title'])) 

我通过 Processing 运行该方法:

# c = instance of my crawling class 
# cs = returns the `lesson_data` for `download_lesson` method 
 
p = Pool(1) 
p.map(c.download_lesson, cs) 

所以一切都很好,因为我正在使用 processes=1在Pool .但是当我运行多个进程时,假设 processes=3然后事情开始变得奇怪,我得到了一个接一个的多个进展。

我在 tqdm documentation 中找到了position 有参数.这清楚地说明了我在这种情况下需要做的事情的目的。

position : int, optional Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).

但是,我不知道如何设置那个位置。我尝试了一些奇怪的东西,比如添加一个应该自增一个的变量,但是每当方法 download_lesson正在运行,它似乎没有做任何递增。总是0所以位置总是0 .

看来我在这种情况下不太了解...欢迎提供任何提示、提示或完整的解决方案。谢谢!


更新 #1:

我发现我也可以将另一个参数传递给 map ,所以我传递了正在设置的进程数量。 (例如进程=2)

p = Pool(config['threads']) 
p.map(c.download_lesson, cs, range(config['threads'])) 

因此,在我的方法中,我尝试打印出该参数,实际上我确实得到了 0和 1 ,因为我正在运行 2示例中的流程。

但这似乎根本没有做任何事情......

progress = tqdm( 
    total=int(response.headers['Content-Length']), 
    unit='B', 
    unit_scale=True, 
    position=progress_position 
) 

我仍然遇到进度条重叠的问题。当我手动将位置设置为(例如 10)时,它会在终端中跳转,因此位置确实会移动,但仍然重叠 ofc,因为现在两者都设置为 10。但是当动态设置时,它似乎也不起作用。我不明白我的问题是什么...就像 map 两次运行此方法一样,它仍然为两个进度条提供最新的设置位置。我到底做错了什么?

请您参考如下方法:

好的,首先我要感谢@MikeMcKerns 的评论... 所以我的脚本有很多变化,因为我想要不同的方法,但最终归结为这些重要变化。

我的 init.py 现在看起来干净多了...

from scraper.Crawl import Crawl 
 
if __name__ == '__main__': 
    Crawl() 

我在 scraper.Crawl 类中的方法,对于 download_lesson,现在看起来像这样......

def download_lesson(self, lesson): 
 
    response = requests.get(lesson['link'], stream=True) 
    chunk_size = 1024 
 
    progress = tqdm( 
        total=int(response.headers['Content-Length']), 
        unit='B', 
        unit_scale=True 
    ) 
 
    with open(lesson['file'], 'wb') as file: 
        for chunk in response.iter_content(chunk_size=chunk_size): 
            progress.update(len(chunk)) 
            file.write(chunk) 
 
    progress.close() 

最后,我有一个专用于多处理的方法,如下所示:

def begin_processing(self): 
    pool = ThreadPool(nodes=Helper.config('threads')) 
 
    for course in self.course_data: 
        pool.map(self.download_lesson, course['lessons']) 
        print( 
            'Course "{course_title}" has been downloaded, with total of {lessons_amount} lessons.'.format( 
                course_title=course['title'], 
                lessons_amount=len(course['lessons']) 
            ) 
        ) 

如您所知,我对我的类做了一些重大更改,但最重要的是我必须将这一点添加到我的 init.py

if __name__ == '__main__': 

其次,我必须使用@MikeMcKerns 建议我看一看的内容:

from pathos.threading import ThreadPool

因此,通过这些更改,我终于让一切都按我需要的方式工作。这是一个快速屏幕截图。

即便如此,我仍然不知道为什么 pathos.multiprocessing 使 tqdm 进度非常错误,感谢 Mike 的建议,我设法解决了我的问题。谢谢!