【问题标题】:How to loop through output in Luigi如何在 Luigi 中循环输出
【发布时间】:2021-08-21 17:36:42
【问题描述】:

我正在尝试使用 Luigi 构建一个小的抓取管道,并且我正在使用 Pillow 来保存我抓取的页面中的图像。但是,当我尝试将每个图像保存在循环中时(例如,我想将 img_1、img_2、img_3 等保存在输出文件夹中),我正在努力解决输出问题。我试图在输出函数中传递一个“image_id”参数,但它不起作用,我不知道如何完成。

class DownloadImages(luigi.Task):

    def requires(self):
        pass # taking out dependencies for this example

    def output(self, image_id):
        return luigi.LocalTarget(f"img/img_{image_id}.jpeg")

    def run(self):
        resp = requests.get("https://my-site.com")
        soup = BeautifulSoup(resp.content, "html.parser")
        images_list = soup.select("img")
        for image_id in range(len(images_list)):
            image_url = images_list[image_id]["src"]
            img = Image.open(requests.get(image_url, stream=True).raw)
            img.save(self.output(image_id).path)

【问题讨论】:

  • “它不起作用”是什么意思?会发生什么?
  • 我明白了:TypeError: output() missing 1 required positional argument: 'image_id'
  • 检查您是否正在运行您在屏幕上看到的内容,或者您​​的调试器中是否还有旧文件
  • 错误消息似乎与您向我们显示的代码不匹配。请更正其中一项。
  • 我从本地调度程序运行工作流:“python -m luigi --module scraper DownloadImages”。根据@LukasSchmid 的回答,该代码作为标准 Python 类可以正常工作,但在 Luigi 中,任务因上述错误而失败。

标签: python luigi


【解决方案1】:

新的答案,因为它完全不同: python -m luigi --module scraper DownloadImages --local-scheduler

from PIL import Image
import requests
import luigi

class DownloadImages(luigi.Task):
    save_path = f"img/*.jpg"

    def output(self):
        return luigi.LocalTarget(self.save_path)

    def run(self):
        img_ids = [1,2,3]
        self.imgs = []
        for img_id in img_ids:
            img = Image.open(requests.get("https://i.kym-cdn.com/entries/icons/original/000/000/007/bd6.jpg", stream=True).raw)
            img.save(self.save_path.replace("*", f"img_{img_id}"))

luigi 的重点是要有一个工作流程。它使用output 在任务之间传递数据的位置。你不能有额外的参数,因为你不应该调用那个函数(除了获取你想要保存输出的位置)。

免责声明:我也可能用错了。请去看看Documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多