簡體   English   中英

Python:分支工作流程/管道的現有解決方案?

[英]Python: existing solution for branching workflow/pipeline?

在我的應用程序中,我實現了一個非常粗糙的工作流程,該工作流程由5個不同的“處理單元”組成。 目前的代碼結構如下:

def run(self, result_first_step=None, result_second_step=None):

    config = read_workflow_config("config.ini")

    if config.first_step:
        result_first_step = run_process_1()

    if config.second_step and result_first_step is not None:
        result_second_step = run_process_2(result_first_step)
    else:
        raise Exception("Missing required data")

    if config.third_step:
        result_third_step = run_process_3(result_first_step, result_second_step)
    else:
        result_third_step = None

    collect_results(result_first_step, result_second_step, result_third_step)

等等。 該代碼可以工作,但幾乎不可維護且非常脆弱(處理過程比此簡化示例要復雜得多)。 因此,我一直在考慮采用另一種策略,即使用以下方法制定適當的工作流程:

  • 短路:我不能給啟動過程提供任何數據,也不能提供兩種不同類型的數據。 在后一種情況下,工作流程會短路並跳過某些處理
  • 通用對象:所有設備均可使用類似填料的配置
  • 條件:根據配置,某些位可能會被跳過

是否有可用的Python庫來執行這些類型的工作流程,還是應該自己滾動? 我一直在嘗試pyutilib.workflow,但是它無法正確地支持通用配置對象,因為它無法將其傳遞給所有工作人員(乏味)。

注意:這是針對庫/命令行應用程序的,因此基於Web的工作流解決方案不合適。

Python中有很多方法可以使用管道,從半頁到...
這是主要思想:在頂部,將所有步驟定義放入dict中;
然后管道(例如“ CAT”)執行步驟C,A,T。

class Pipelinesimple:
    """p = Pipelinesimple( funcdict );  p.run( "C A T" ) = C(X) | A | T

    funcdict = dict( A = Afunc, B = Bfunc ... Z = Zfunc )
    pipeline = Pipelinesimple( funcdict )
    cat = pipeline.run( "C A T", X )  # C(X) | A | T, i.e. T( A( C(X) ))
    dog = pipeline.run( "D O G", X, **kw )  # D(X, **kw) | O(**kw) | G(**kw)
    """

def __init__( self, funcdict ):
    self.funcdict = funcdict  # funcs or functors of X

def run( self, steps, X, **commonargs ):
    """ steps "C A T" or ["C", "A", "T"]
        all funcs( X, **commonargs )
    """

    if isinstance( steps, basestring ):
        steps = steps.split()  # "C A T" -> ["C", "A", "T"]
    for step in steps:
        func = self.funcdict(step)
        # if X is None: ...
        X = func( X, **commonargs )
    return X

接下來,有幾種方法可以為不同的步驟提供不同的參數。

一種方法是解析多行字符串,例如

""" C  ca=5  cb=6 ...
    A  aa=1 ...
    T  ...
"""

另一個是獲取功能/功能名稱/參數字典的列表,例如

pipeline.run( ["C", dict(ca=5, cb=6), lambda ..., "T", dict(ta=3) ])

第三個是分裂PARAMS“A__aa B__ba ......”的方式sklearn.pipeline.Pipeline 做。 (這是針對機器學習的,但是您可以復制管道部分。)

每一個都有明顯的利弊。

一大批才華橫溢的人才可以很快提出許多解決問題的原型解決方案[管道]。
但是將一打減少到兩個或三個需要永遠。

無論采用哪種方式,都可以提供一種記錄所有運行參數的方式。

也可以看看:
篩選類型
py

您可以將run方法變成生成器;

def run(self)
  result_first_step = run_process_1()
  yield result_first_step
  result_second_step = run_process_2(result_first_step)
  yield result_second_step
  result_third_step = run_process_3(result_first_step, result_second_step)
  collect_results(result_first_step, result_second_step, result_third_step)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM