python click app is failing with indication of “missing argument” but cannot locate the issue

流过昼夜 提交于 2019-12-13 00:32:06

问题


I am creating an app with Click in python 3.6. I seem to have an error that I cannot find. I have posted my code below.

The problem is that when I type:

python clickapp.py --help

all is good. But when I type

python clickapp.py simplerequest --help

I get an error indicating that I am missing the argument "directory", but there is no traceback to indicate the source of the error. The exact output is:

Usage: clickapp.py [OPTIONS] STARTDATE ENDDATE DIRECTORY COMMAND [ARGS]...

Error: Missing argument "directory".

Here is the code that I used. This is a minimal example with filename clickapp.py.

import click

@click.group()
@click.argument('startdate')
@click.argument('enddate')
@click.argument('directory', type=click.Path())
@click.pass_context
def cli(ctx,
        startdate,
        enddate,
        directory):

    ctx.obj['directory'] = directory 
    ctx.obj['startdate'] = startdate
    ctx.obj['enddate'] = enddate


@click.command()
@click.argument('arg1', type=str)
@click.argument('arg2', type=click.Path(exists=True))
@click.argument('arg3', type=int)
@click.pass_context
def SimpleRequest(ctx,
                  arg1,
                  arg2,
                  arg3):

    """Simple request processor"""

    ctx.obj['arg1'] = arg1
    ctx.obj['arg2'] = arg2
    ctx.obj['arg3'] = arg3

cli.add_command(SimpleRequest)

if __name__ == '__main__':
    cli(obj={})

Can anyone see the source of the error?

I tried a few things:

  1. I removed the type=click.Path(exists=True) in arg2 to see if that might be causing the problem. But that did not change anything.

  2. I also tried to remove some validation logic around inserting the variables into the ctx dictionary, but that did not help either.


回答1:


Your help parsing problem is that click is attempting to fill in the startdate endate directory arguments first.

So your simplerequest --help fills in the first two and then it complains that the third (directory) is missing.

Usually the command (simplerequest) would be the first argument. You could then add optional args before, since click can easily distinguish those from the command.

Or you could coerce click to see the first arg as a valid command and do the help anyways, but this is non-standard and would require some code. Also it would preclude the command name being the start date, although they are likely easily differentiated.



来源:https://stackoverflow.com/questions/47272584/python-click-app-is-failing-with-indication-of-missing-argument-but-cannot-loc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!