Skip to main content
 首页 » 编程设计

python argparse 喜欢 --home-path

2024年10月01日7yyy_WW

我有一个问题,我找不到答案。这是我的代码块:

import argparse 
 
parser = argparse.ArgumentParser() 
parser.add_argument('-t', '--test', help='just for testing') 
parser.add_argument('--home-path', help='specify the homepath') 
args = parser.parser_args() 
if args.test: 
        print('Test') 

如何像测试参数一样访问“--home-path”参数?

请您参考如下方法:

只需将属性名称中的-替换为_即可:

args = parser.parse_args() 
if args.home_path: 
    # Do stuff 

此行为记录在 dest 下在 ArgumentParser.add_argument() :

For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name.