简体   繁体   English

蟒蛇 2.7。 解析输入参数

[英]Python 2.7. Parse input parameters

Good time of the day!一天中的好时光! First of all, let me say that I'm a newbie in Python world.首先,让我说我是 Python 世界的新手。 I've problems with parsing input parameters.我在解析输入参数时遇到问题。 At this moment I'm using Python 2.7 and module which is called argparse .目前我正在使用 Python 2.7和名为argparse模块。 I'm trying to design simple application which will be able to parse simple input parameters.我正在尝试设计能够解析简单输入参数的简单应用程序。 Here is a short example:这是一个简短的例子:

my_app.py sync --force my_app.py 同步 --force

Second example:第二个例子:

my_app.py patch --branch my_app.py 补丁 --branch

I see that for this I can use add_argument which can work with positional and optional arguments.我看到为此我可以使用add_argument ,它可以与位置和可选参数一起使用。 Like in my case I want to have few positional (but optional at the same time) and few optional arguments.就像在我的情况下,我想要很少的位置(但同时是可选的)和一些可选的参数。 To do that I've design small script为此,我设计了小脚本

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='My App')
    parser.add_argument('sync', type=bool, const=True, nargs='?')
    parser.add_argument('-f', '--force', dest='sync_force', type=bool, const=True, nargs='?')
    parser.add_argument('-b', '--branch', type=str, const=True, nargs='?')
    parser.add_argument('-u', '--url', type=str, const=True, nargs='?')
    parser.add_argument('patch', type=bool, const=True, nargs='?')
    parser.add_argument('revert', type=bool, const=True, nargs='?')
    parser.add_argument('verify', type=bool, const=True, nargs='?')

    values = parser.parse_args()

    if values.revert:
        handler.revert()
    else:
        parser.print_help()

I see that I can use nargs='?'我看到我可以使用nargs='?' to specify the positional parameter as optional, but each time when I'm calling my script it shows like I got ' sync ' as input parameter, even if I specified ' patch '.将位置参数指定为可选,但是每次我调用我的脚本时,它都会显示我将 ' sync ' 作为输入参数,即使我指定了 ' patch '。 So, I think that it shows just first added element.所以,我认为它只显示了第一个添加的元素。 Could you tell me what's wrong and where is a problem?你能告诉我出了什么问题,哪里出了问题吗?

Update: I'm trying to achieve a situation when I will be able to have only one positional argument at the same time(and at least one, but with any additional optional parameters).更新:我试图实现一种情况,即我将能够同时只有一个位置参数(并且至少有一个,但带有任何其他可选参数)。 For example例如

my_app.py sync my_app.py 同步

my_app.py path my_app.py 路径

my_app.py verify --force my_app.py 验证 --force

my_app.pyrevert --branch my_app.pyrevert --branch

With:和:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='My App')
    parser.add_argument('cmd', choices=['sync','patch', 'revert','verify'])
    parser.add_argument('-f', '--force', action='store_true')
    parser.add_argument('-b', '--branch')
    parser.add_argument('-u', '--url')

    args = parser.parse_args()
    print(args)
    if args.cmd in ['revert']:
        print('handler.revert()')
    else:
        parser.print_help()

testing测试

1243:~/mypy$ python stack60327766.py 
usage: stack60327766.py [-h] [-f] [-b BRANCH] [-u URL]
                        {sync,patch,revert,verify}
stack60327766.py: error: too few arguments
1244:~/mypy$ python stack60327766.py revert
Namespace(branch=None, cmd='revert', force=False, url=None)
handler.revert()
1244:~/mypy$ python stack60327766.py revert -f -b foobar -u aurl
Namespace(branch='foobar', cmd='revert', force=True, url='aurl')
handler.revert()
1244:~/mypy$ python stack60327766.py verify-f -b foobar -u aurl
usage: stack60327766.py [-h] [-f] [-b BRANCH] [-u URL]
                        {sync,patch,revert,verify}
stack60327766.py: error: argument cmd: invalid choice: 'verify-f' (choose from 'sync', 'patch', 'revert', 'verify')
1245:~/mypy$ python stack60327766.py verify -f -b foobar -u aurl
Namespace(branch='foobar', cmd='verify', force=True, url='aurl')
usage: stack60327766.py [-h] [-f] [-b BRANCH] [-u URL]
                        {sync,patch,revert,verify}

My App

positional arguments:
  {sync,patch,revert,verify}

optional arguments:
  -h, --help            show this help message and exit
  -f, --force
  -b BRANCH, --branch BRANCH
  -u URL, --url URL

argparse has native support for subcommands . argparse命令本机支持

Adapting from the above-linked documentation,改编自上述链接的文档,

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
subparsers = parser.add_subparsers()
sync_parser = subparsers.add_parser('sync')
patch_parser = subparsers.add_parser('patch')
revert_parser = subparsers.add_parser('revert')
verify_parser = subparsers.add_parser('verify')

etc. is probably what you're looking for.等可能是你正在寻找的。

Beyond that, I can only recommend the Click library for a more fluent interface for CLIs.除此之外,我只能推荐Click库以获得更流畅的 CLI 界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM