如何在日志文件名中使用时间戳保存python luigi终端输出到日志文件中

时间:2019-01-29 01:21:35

标签: python-3.x logging luigi

我有一个简单的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文档,它并没有太大帮助。一个简单的例子将不胜感激。

1 个答案:

答案 0 :(得分:0)

您只需将以下内容更改为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()
相关问题