gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:38:26 25 4
gpt4 key购买 nike

我有

fruits = [ apple, banana , pineapple, oranges]
size = [ small, medium, large]
fruitproperties = [ color, weight]

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

以下是我的代码:

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

我想做到如下:

maindir is compulsory argument 
fruit name is optional argument

喜欢

file.py <maindirpath> 

将为所有目标进行编译

file.py <maindirpath> -p fruitname给出它只会针对该水果进行编译。对于它的所有组合例如:

apple-small, apple-medium and apple-large. 

最佳答案

使用 docopt 的另一个解决方案,使用人类可读的文档字符串配置您的选项解析器:

#!/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)
<小时/>

docopt 检查语法正确性并返回字典中的给定选项:

$ ./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'}

关于python - 如何在Python中进行选项参数解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31296853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com