【问题标题】:How to use a variable number of arguments in pyinvoke如何在 pyinvoke 中使用可变数量的参数
【发布时间】:2016-06-16 18:16:15
【问题描述】:

我想在 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!

类似,如果我定义 pdf_combine(out_file, in_file),in_file 之前没有星号

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

如果我只使用下面的一个 in_file 调用任务,它运行正常。

$ 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 的文档中找不到类似的东西,尽管我无法想象这个库的其他用户不需要调用具有可变数量参数的任务...

【问题讨论】:

  • 您遇到错误了吗?如果是这样,请在您的问题中包含回溯。
  • 谢谢,没有回溯,问题更多是关于使用 pyinvoke 库。我用几个例子修正了我的问题以进行澄清。
  • 我不确定您使用的是哪个版本的调用 - 但您需要使用 invoke pdf-combine (注意它是一个破折号而不是下划线 - 如果他们有一个参数,则在参数中这样做docs.pyinvoke.org/en/stable/concepts/…)

标签: python pyinvoke


【解决方案1】:

你可以这样做:

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 文档,我找不到其他方法。

【讨论】:

  • 谢谢。这看起来是一个实用且干净的解决方案。我很高兴我没有遗漏文档中的任何内容。同时,我使用了 argparse 模块。它还需要 20 分钟才能理解,但值得这样做。我只是瞥见了它的力量。当然,pyinvoke 的目标与 argparse 不同。很公平。
【解决方案2】:

0.21.0 版本开始,您可以使用iterable flag values

@task(
  help={
      'out-file': 'Name of the output file.', # `out-file` NOT `out_file`
      'in-files': 'List of the input files.'},
  iterable=['in_files'],
)
def pdf_combine(out_file, in_files):
    for item in in_files:
        print(f"file: {item}")

注意help 使用破折号转换键,iterable 使用非转换下划线键

注意我知道上面的注释有点奇怪,所以我提交了PR,因为作者非常棒,可能会考虑这个建议

以这种方式使用它允许这种类型的 cli:

$ invoke pdf-combine -o spam -i eggs -i ham
  file: eggs
  file: ham

$ invoke --help pdf-combine
Usage: inv[oke] [--core-opts] pdf-combine [--options] [other tasks here ...]

Docstring:
  none

Options:
  -i, --in-files                 List of the input files
  -o STRING, --out-file=STRING   Name of the output file.

注意 pdf_combine 任务是在 CLI 中使用 inv pdf-combine 调用的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2020-04-10
    • 2015-12-01
    • 2012-03-03
    相关资源
    最近更新 更多