首页 > 解决方案 > 如何在我的主函数中同时运行一个类?

问题描述

我想main()同时在我的函数中调用和运行一个类。我的代码中有不同的方法,我想同时运行concurrent.futures它们,我发现我可以把它们放在 a 中class

这是我到目前为止所尝试的:

import requests
import time
import concurrent.futures

img_urls = [
    'https://images.unsplash.com/photo-1516117172878-fd2c41f4a759',
    'https://images.unsplash.com/photo-1532009324734-20a7a5813719',
    'https://images.unsplash.com/photo-1524429656589-6633a470097c',
    'https://images.unsplash.com/photo-1530224264768-7ff8c1789d79'
]

t1 = time.perf_counter()


class Download:
    def __init__(self, img_url):
        self.img_url = img_url

    def download_image(self, img_url):
        img_bytes = requests.get(self.img_url).content
        return img_bytes

    def image_name(self, img_bytes):
        img_bytes = download_image(self, img_url)
        img_name = self.img_url.split('/')[3]
        img_name = f'{img_name}.jpg'
        with open(img_name, 'wb') as img_file:
            img_file.write(img_bytes)
            print(f'{img_name} was downloaded...')

    def run(self):
        download_image(self, img_url)
        image_name(self, img_bytes)


def main():
    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.map(Download, img_urls)

if __name__ == "__main__":
    main()

t2 = time.perf_counter()

print(f'Finished in {t2-t1} seconds')

标签: pythonclassconcurrent.futures

解决方案


据我了解,您想同时执行不同Download对象的运行功能。

首先是run函数有语法错误,应该是:

def run(self):
    img_bytes = download_image(self, img_url)
    image_name(self, img_bytes)

否则img_bytes未定义。

然后您需要将正确的可调用对象传递给执行程序。如果你传递类Download,它只会创建它的一个实例,不会真正调用run方法;每次下载类似这样的新实例应该工作时都这样做:

executor.map(lambda url: Download(url).run, img_urls)

推荐阅读