argparse python模块的文档虽然非常棒,但对于我这个初学者来说,现在还难以理解。我不需要在命令行上做数学运算,也不需要在屏幕上修改格式行或更改选项字符。我想做的就是“如果arg是A,做这个,如果B做那个,如果以上都没有显示帮助并退出”。


当前回答

这是一个新手,但是将Python与Powershell结合起来并使用这个模板,灵感来自深入而伟大的Python命令行参数-真正的Python

在init_argparse()中可以做很多事情,这里我只介绍最简单的场景。

import argparse use if __name__ == "__main__": main() pattern to execute from terminal parse arguments within the main() function that has no parameters as all define a init_argparse() function create a parser object by calling argparse.ArgumentParser() declare one or more argumnent with parser.add_argument("--<long_param_name>") return parser parse args by creating an args object by calling parser.parse_args() define a function proper with param1, param2, ... call function_proper with params being assigned as attributes of an args object e.g. function_proper(param1=args.param1, param2=args.param2) within a shell call the module with named arguments: e.g. python foobar.py --param1="foo" --param2=="bar"

#file: foobar.py
import argparse

def function_proper(param1, param2):
    #CODE...

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument("--param1")
    parser.add_argument("--param2")
    return parser


def main() -> None:
    parser = init_argparse()
    args = parser.parse_args()
    function_proper(param1=args.param1, param2=args.param2)


if __name__ == "__main__":
    main()
>>> python .\foobar.py --param1="foo" --param2=="bar"

其他回答

这是一个新手,但是将Python与Powershell结合起来并使用这个模板,灵感来自深入而伟大的Python命令行参数-真正的Python

在init_argparse()中可以做很多事情,这里我只介绍最简单的场景。

import argparse use if __name__ == "__main__": main() pattern to execute from terminal parse arguments within the main() function that has no parameters as all define a init_argparse() function create a parser object by calling argparse.ArgumentParser() declare one or more argumnent with parser.add_argument("--<long_param_name>") return parser parse args by creating an args object by calling parser.parse_args() define a function proper with param1, param2, ... call function_proper with params being assigned as attributes of an args object e.g. function_proper(param1=args.param1, param2=args.param2) within a shell call the module with named arguments: e.g. python foobar.py --param1="foo" --param2=="bar"

#file: foobar.py
import argparse

def function_proper(param1, param2):
    #CODE...

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument("--param1")
    parser.add_argument("--param2")
    return parser


def main() -> None:
    parser = init_argparse()
    args = parser.parse_args()
    function_proper(param1=args.param1, param2=args.param2)


if __name__ == "__main__":
    main()
>>> python .\foobar.py --param1="foo" --param2=="bar"

下面是我使用argparse(使用多个args)的方法:

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

Args将是一个包含参数的字典:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

在您的情况下,只需添加一个参数。

补充一下其他人已经说过的话:

我通常喜欢使用'dest'参数指定变量名,然后使用'globals().update()'将这些变量放在全局命名空间中。

用法:

$ python script.py -i "Hello, World!"

代码:

...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"

我浏览了所有的例子和答案,但在某种程度上,它们并没有满足我的需求。所以我会给她列出一个我需要更多帮助的场景,我希望这能更好地解释这个想法。

最初的问题

我需要开发一个工具,它得到一个文件来处理它,它需要一些可选的配置文件来配置工具。

所以我需要的是以下内容

mytool.py file.text -config config-file.json

解决方案

下面是解决方案代码

import argparse

def main():
    parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
    parser.add_argument('filename', help="Input file either text, image or video")
    # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
    # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
    parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

    args = parser.parse_args()
    
    filename = args.filename
    configfile = args.config_file

    print("The file to be processed is", filename)
    print("The config file is", configfile)

    if args.debug:
        print("Debug mode enabled")
    else:
        print("Debug mode disabled")

    print("and all arguments are: ", args)

if __name__ == '__main__':
    main()

我将在多个增强中展示解决方案,以展示其思想

第一轮:列出论点

将所有输入列为强制输入,因此第二个参数为

parser.add_argument('config_file', help="a JSON file to load the initial configuration ")

当我们获得该工具的帮助命令时,会发现以下结果

(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename     Input file either text, image or video
  config_file  a JSON file to load the initial configuration

optional arguments:
  -h, --help   show this help message and exit

当我像下面这样执行它时

(base) > python .\argparser_example.py filename.txt configfile.json

结果将是

The file to be processed is filename.txt
The config file is configfile.json
and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')

但是配置文件应该是可选的,我从参数中删除了它

(base) > python .\argparser_example.py filename.txt

结果将是:

usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c

也就是说我们的工具有问题

第二轮:优化

因此,为了使它成为可选的,我修改了程序如下

    parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)

帮助的结果应该是

usage: argparser_example.py [-h] [-c CONFIG] filename

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename              Input file either text, image or video

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        a JSON file to load the initial configuration

所以当我执行程序时

(base) > python .\argparser_example.py filename.txt

结果将是

The file to be processed is filename.txt
The config file is configFile.json
and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')

有这样的论点

(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json

结果将是

The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')

第三轮:增强

要将标志名从——config_file更改为——config,同时保持变量名不变,我们修改代码,包括dest='config_file',如下所示:

parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')

命令是

(base) > python .\argparser_example.py filename.txt --config anotherConfig.json

为了增加对调试模式标志的支持,我们需要在参数中添加一个标志来支持布尔调试标志。为了实现它,我添加了以下内容:

    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

工具命令如下:

(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug

结果将是

The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')

最简单的答案!

附注:编写argparse文档的人是愚蠢的

python代码:

import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set

运行代码

python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1