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

查看:22
本文介绍了如何访问名称中带点的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 会将所有属性添加到带有 setattr.因此,您可以使用 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天全站免登陆