如何在python中进行选项参数解析?

如何在python中进行选项参数解析?,python,Python,我有 我的脚本旨在为所有水果和大小组合的水果属性创建txt文件。 目前,我从命令行获取maindirectory作为参数。并编译所有组合的输出 以下是我的代码: fruits = [ apple, banana , pineapple, oranges] size = [ small, medium, large] fruitproperties = [ color, weight] 我想这样做: parser = argparse.ArgumentParser(description =

我有

我的脚本旨在为所有水果和大小组合的水果属性创建txt文件。 目前,我从命令行获取maindirectory作为参数。并编译所有组合的输出

以下是我的代码:

fruits = [ apple, banana , pineapple, oranges]
size = [ small, medium, large]
fruitproperties = [ color, weight] 
我想这样做:

parser = argparse.ArgumentParser(description = 'Maindirectory required')
parser.add_argument('maindir' help = ' give maindir path', action = 'store')
args = parser.parse_args() 


您可以将可选元素添加到

一些例子:

  • 至少需要
    maindir

    import argparse
    
    parser = argparse.ArgumentParser(description = 'Maindirectory required')
    parser.add_argument('maindir', help = ' give maindir path', action = 'store')
    parser.add_argument("-p", "--printfruit", help="print specific fruit", type=str)
    args = parser.parse_args() 
    print args.maindir
    print args.printfruit
    
    >python test.py
    usage: test.py [-h] [-p PRINTFRUIT] maindir
    test.py: error: too few arguments
    
  • 提供
    maindir

    import argparse
    
    parser = argparse.ArgumentParser(description = 'Maindirectory required')
    parser.add_argument('maindir', help = ' give maindir path', action = 'store')
    parser.add_argument("-p", "--printfruit", help="print specific fruit", type=str)
    args = parser.parse_args() 
    print args.maindir
    print args.printfruit
    
    >python test.py
    usage: test.py [-h] [-p PRINTFRUIT] maindir
    test.py: error: too few arguments
    
  • 同时提供
    maindir
    和可选值

    >python test.py C:\Fruits
    C:\Fruits
    None
    

如果我正确理解了您的评论,那么如果某些参数不存在,那么您将使用默认参数。您可以提供
default
参数,并对其进行一些操作,使其成为一个列表:

>python test.py C:\Fruits -p apple
C:\Fruits
apple
现在,在程序的其余部分使用
fruit
变量,而不是
args.printfruit

产出:

  • 没有水果

    parser.add_argument("-p", "--printfruit", help="print specific fruit", type=str, default="apple, pineapple, banana")
    args = parser.parse_args() 
    fruit = [str(item) for item in args.printfruit.split(',')]
    
  • 有水果价值

    >python test.py C:\Fruits
    C:\Fruits
    apple, pineapple, banana            # This is args.printfruit
    ['apple', ' pineapple', ' banana']  # This is the fruits variable
    
使用另一种解决方案,使用人类可读的docstring配置选项解析器:

>python test.py C:\Fruits -p apple
C:\Fruits
apple        # This is args.printfruit
['apple']    # This is the fruits variable

那么问题是什么呢?目前我只使用maindir作为参数,并为所有组合编译。我还想添加一个特性,这样用户就可以指定水果名称,并为该水果的所有组合进行编译。若用户并没有指定,它将为所有水果编译。case中的用户应该给出file.py-p froutnamei是python新手。不知道如何使参数解析成为可选的。谢谢。基本上这是我的可选论点和第二个论点。sys.argv[2]。我剩下的代码将使用它。那么,如果这个可选参数存在,我怎么写呢,do fruit=sys.argv[2]else fruits=[苹果、菠萝、香蕉]非常感谢。是的,我也想要一样的。我只有一个疑问。目前,我将maindir=sys.argv[1]{这是我的强制参数-maindirectory},现在是fruit=sys.argv[2]。现在的情况是:如果可选参数不存在,那么我的代码将只使用maindir。但有时会给出可选参数,如果这种情况下我必须使其为fruit=sys.argv[2]。并使用它。如何在代码中添加此条件?如果给出了可选参数,那么fruit=sys.argv[2]else fruits=[apple,banana,菠萝]检查sys.argv[2]是否为
None
。如果不是,则将
fruit
设置为已传递的值,否则默认为列表中的值。或者,将一个
try/except
环绕在赋值
fruit=sys.argv[2]
上,如果捕获了一个
索引器
,则不会得到一个通过的值并将
fruit
赋值给默认值。
>python test.py C:\Fruits -p apple
C:\Fruits
apple        # This is args.printfruit
['apple']    # This is the fruits variable
#!/usr/bin/env python3
# coding: utf-8
"""Print Fruit permutations.

Usage:
    fruit.py <maindirpath> [--printfruit=<fruit>...]
    fruit.py --help

Arguments:
    <maindirpath>  Base directory to create files in

Options:
    -p, --printfruit=<fruit>  specify fruit to print
    -h, --help                display this help and exit
"""

from docopt import docopt

if __name__ == '__main__':
    args = docopt(__doc__)
    print(args)
$ ./fruit.py
Usage:
    fruit.py <maindirpath> [--printfruit=<fruit>...]
    fruit.py --help

$ ./fruit.py foobar
{'--help': False,
 '--printfruit': [],
 '<maindirpath>': 'foobar'}

$ ./fruit.py foobar -p apple -p banana
{'--help': False,
 '--printfruit': ['apple', 'banana'],
 '<maindirpath>': 'foobar'}