2016-03-03 58 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

相关问题