2016-03-03 71 views
5

我想在pyinvoke的任務中使用可變數量的參數。 像這樣:如何在pyinvoke中使用可變數量的參數

from invoke import task 

@task(help={'out_file:': 'Name of the output file.', 
      'in_files': 'List of the input files.'}) 
def pdf_combine(out_file, *in_files): 
    print("out = %s" % out_file) 
    print("in = %s" % list(in_files)) 

以上只是我嘗試了許多變化中的一種,但它似乎pyinvoke不能處理可變數量的參數。這是真的?

$ invoke pdf_combine -o binder.pdf -i test.pdf test1.pdf 
No idea what '-i' is! 

類似上面的代碼的結果,如果我之前in_file中

$ invoke pdf_combine -o binder.pdf -i test.pdf test1.pdf 
No idea what 'test1.pdf' is! 

定義pdf_combine(out_file,in_file中),沒有星號。如果我調用任務與像只有一個in_file中在它下面運行OK。

$ invoke pdf_combine -o binder.pdf -i test.pdf 
out = binder.pdf 
in = ['t', 'e', 's', 't', '.', 'p', 'd', 'f'] 

我想看到的是

$ invoke pdf_combine -o binder.pdf test.pdf test1.pdf test2.pdf 
out = binder.pdf 
in = [test.pdf test1.pdf test2.pdf] 

pyinvoke的文檔中我找不到這樣的事情,雖然我無法想象,這個庫的其他用戶不必爲需要與調用的參數數目可變任務...

+0

您是否收到錯誤?如果是的話,請在你的問題中包含回溯。 – Forge

+0

謝謝,沒有回溯,問題更多地是關於使用pyinvoke庫。我用幾個例子來澄清我的問題。 – Killwas

回答

3

你可以做這樣的事情:

from invoke import task 

@task 
def pdf_combine(out_file, in_files): 
    print("out = %s" % out_file) 
    print("in = %s" % in_files) 
    in_file_list = in_files.split(',') # insert as many args as you want separated by comma 

>> out = binder.pdf 
>> in = test.pdf,test1.pdf,test2.pdf 

invoke命令是:

invoke pdf_combine -o binder.pdf -i test.pdf,test1.pdf,test2.pdf 

我無法找到另一種方式來做到這一點閱讀pyinvoke文檔。

+1

謝謝。這看起來像一個實用而乾淨的解決方案。我很高興我沒有錯過任何文檔。 同時我使用了argparse模塊。它需要20分鐘才能理解,但值得做。我只是看到了它的力量。 當然,pyinvoke的目標並不像argparse一樣。很公平。 – Killwas