修饰符在Python中生成一组连续的任务?

修饰符在Python中生成一组连续的任务?,python,scipy,distributed-computing,pipeline,Python,Scipy,Distributed Computing,Pipeline,我正在编写一个程序,按顺序执行一组任务。每个任务都是一个输出新文件的函数,但如果文件名已存在,则不应执行任何给定任务。我发现自己一次又一次地写这种代码: task1_fname = task1() # come up with filename for next task task2_fname = "task2.txt" if not os.path.isfile(task2_fname): # task2 might depend on task1's output, so it get

我正在编写一个程序,按顺序执行一组任务。每个任务都是一个输出新文件的函数,但如果文件名已存在,则不应执行任何给定任务。我发现自己一次又一次地写这种代码:

task1_fname = task1()
# come up with filename for next task
task2_fname = "task2.txt"
if not os.path.isfile(task2_fname):
  # task2 might depend on task1's output, so it gets task1's filename
  task2(task1_fname)
task3_fname = "task3.txt"
if not os.path.isfile(task3_fname):
  task3(...)
基本思想是,如果文件存在(理想情况下为非空),则不应执行生成此文件的任务

不必每次都编写
os.path.isfile
调用,最好的Python方式是什么?装饰师能更简洁地表达这一点吗?或者类似于:

with task2(task1_fname):
  # continue to next task

有什么想法吗?

你在找这样的东西吗

def preserve_output(f):
    def wrap(input, output):
        if not os.path.isfile(output):
            f(input, output)
    return wrap

@preserve_output
def task1(input, output):
    ...

@preserve_output
def task2(input, output):
    ...

task1('input', 'output_1')
task2('output_1', 'output_2')
task3('output_2', 'output_3') etc

你在找这样的东西吗

def preserve_output(f):
    def wrap(input, output):
        if not os.path.isfile(output):
            f(input, output)
    return wrap

@preserve_output
def task1(input, output):
    ...

@preserve_output
def task2(input, output):
    ...

task1('input', 'output_1')
task2('output_1', 'output_2')
task3('output_2', 'output_3') etc