python - 如何在我的主函数中同时运行一个类?
问题描述
我想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')
解决方案
据我了解,您想同时执行不同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)
推荐阅读
- reactjs - 更改后反应获取教程不起作用
- elixir - Ecto 连接表验证
- python - PythonQt:我到底是怎么安装它的?
- c# - 使用 .split() 处理超出范围的异常
- php - 以小时为单位的日期函数时间总是返回 1 php
- reactjs - 错误在 Graphiql 上正确显示,但未在反应前端返回到 Apollo 客户端
- java - 尝试返回数组中的单个元素时,如何在 for 循环中修复“缺少返回语句”?
- java - Spring RestTemplate 超时配置不起作用
- javascript - HTML:页面每 5 秒加载一次并显示倒计时,如 5、4、3、2、1,然后重新加载页面
- c# - Unity - 使对象消失一段时间并再次显示