如何访问名称中带点的python argparse参数 [英] How to access a python argparse argument with a dot in the name

查看:30
本文介绍了如何访问名称中带点的python argparse参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的argparse允许我定义参数名称,名称中包含一个点.但是我该如何访问这些?

Python's argparse lets me define argument names containing a dot in the name. But how can I access these ?

import argparse


parser = argparse.ArgumentParser()
parser.add_argument("inputfile.txt")
parser.add_argument("outputfile.txt")

args = parser.parse_args(['hello', 'world'])

# now args is:
# Namespace(inputfile.txt='hello', outputfile.txt='world')


# and this does not work
print(args.inputfile.txt)
>>> AttributeError: 'Namespace' object has no attribute 'inputfile'

很明显,可以在名称中创建一个带有点的属性名称,但是如何访问它们呢?

Obviously attribute names can be created with a dot in their name but how can these be accessed ?

我的目标是让argparse显示inputfile.txt的名称(例如,使用--help),但将属性命名为"inputfile".

My goal was to let argparse display the inputfile.txt name (e.g. with --help) but call the attribute "inputfile".

尝试了一些建议后,最简单的方法是使用metavar选项:

After trying some of the suggestions the easiest way to accomplish this is using the metavar option:

parser.add_argument("inputfile", metavar="inputfile.txt")

推荐答案

在内部, argparse 将使用 getattr :

Internally, argparse will add all attributes to the Namespace() instance with setattr. Accordingly, you can access the values with getattr:

getattr(args, 'inputfile.txt')

但是,这不是那么直观,通常应避免在属性名称中带有圆点.建议使用 dest 选项的 argparse.add_argument 定义自己的变量来存储该参数的值,如hd1在其答案中所建议的.

However, this is not as intuitive and in general attribute names with dots in them should be avoided. It is recommended to use the dest option of argparse.add_argument to define your own variable in which to store the value for that argument, as hd1 suggests in their answer.

这篇关于如何访问名称中带点的python argparse参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆