【问题标题】:How to save python luigi terminal output in log file with timestamp in log file name如何将python luigi终端输出保存在日志文件中,日志文件名中带有时间戳
【发布时间】:2019-01-29 01:21:34
【问题描述】:

我有一个简单的 luigi 管道。

import luigi
import subprocess
import row_count_test


class TaskOne(luigi.Task):


    def requires(self):
        return None

    def run(self): 
        output = row_count_test()
        if output:
            with self.output().open('w') as open_file:
                open_file.write('{}'.format(output))

    def output(self):
        return luigi.LocalTarget('TaskOne.txt')


class TaskTwo(luigi.Task):
    def requires(self):
        return TaskOne()
    def run(self):
        subprocess.call('rm *.txt', shell = True)


if __name__ == "__main__":
    luigi.run()

我通过命令行运行以下代码:

python luigi_demo.py --scheduler-host localhost TaskTwo

我希望能够将终端输出保存到日志文件。我还希望能够在日志文件名中添加时间戳。我知道有一种方法可以通过 bash 命令来实现。有没有办法使用 luigi 做到这一点?我查看了 luigi.cfg 文档,并没有太大帮助。一个简单的例子将不胜感激。

【问题讨论】:

    标签: python-3.x logging luigi


    【解决方案1】:

    您只需将以下内容更改为您的 TaskTwo。

    import datetime as dt
    class TaskTwo(luigi.Task):
    date= luigi.DateSecondParameter(default=dt.datetime.now())
    
    def output(self):
       # Here you create a file  with your date in it.
       return luigi.LocalTarget('path/to/your/log/file%s.txt' % self.date)
    
    def requires(self):
        return TaskOne()
    
    def run(self):
        self.output().open('w') as f:
           subprocess.call('rm *.txt', shell = True,stdout=f)
    

    另外,如果你想删除在 Taskone 中创建的文件,那么你可以删除 run() 中的所有代码,然后添加 self.input().remove()

    class TaskTwo(luigi.Task):
    date= luigi.DateSecondParameter(default=dt.datetime.now())
    
    def output():
       return luigi.LocalTarget('path/to/your/log/file%s.txt' % self.date)
    
    def requires(self):
        return TaskOne()
    
    def run(self):
        # this should remove the file created in the  Task one.
        self.input().remove()
    

    【讨论】:

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