python - 对 argparse 感到困惑
问题描述
我在理解 argparse 的工作原理时遇到了一些麻烦,我已经梳理了文档,但仍然难以理解。
def arguments():
parser = argparse.ArgumentParser(description='Test..')
parser.add_argument("-i", "--input-file", required=True, help="input file name")
parser.add_argument("-o", "--output-file", required=True, help="output file name")
parser.add_argument("-r", "--row-limit", required=True, help="row limit to split", type=int)
args = parser.parse_args()
is_valid_file(parser, args.input_file)
is_valid_csv(parser, args.input_file, args.row_limit)
return args.input_file, args.output_file, args.row_limit
def is_valid_file(parser, file_name):
"""Ensure that the input_file exists"""
if not os.path.exists(file_name):
parser.error("The file {} does not exist".format(file_name))
sys.exit(1)
def is_valid_csv(parser, file_name, row_limit):
"""
Ensure that the # of rows in the input_file
is greater than the row_limit.
"""
row_count = 0
for row in csv.reader(open(file_name)):
row_count += 1
if row_limit > row_count:
parser.error("More rows than actual rows in the file")
sys.exit(1)
上面的代码工作正常,但是一旦我在第 5 行删除“--row-limit”,我会得到一个
Traceback (most recent call last):
File ".\csv_split.py", line 95, in <module>
arguments = arguments()
File ".\csv_split.py", line 33, in arguments
is_valid_csv(parser, args.input_file, args.row_limit)
AttributeError: 'Namespace' object has no attribute 'row_limit'
为什么删除“--row-limit”会出现此错误?
解决方案
args = parser.parse_args()
actually adds an attribute to the namespace args
for each parser.add_argument
call. The name of the attribute is generated from your argument name, here --row-limit
is transformed to row_limit
because you can't have dashes in variable names. See the argparse documentation for details.
So when you call parser.add_argument(..., "--row-limit", ...)
, it creates args.row_limit
once you invoke parse_args()
. As Amadan mentioned, you use args.row_limit
later on in your code. But if you remove the --row-limit
argument from the parser, the attribute row_limit
won't exist in args
.
推荐阅读
- entity-framework - Create 表单需要 EF Core 3.1 Key/Identity 字段,我不知道为什么
- firebase - 如何为推送通知设置持续集成测试?
- javascript - 使用正则表达式获取特定字符串
- excel - 为视力受损的用户放大单个单元格的内容
- python - Django 项目“配置不当:请求的设置安装应用程序”错误
- sql - 在 SQL 中将 STRING_SPLIT 用于分隔值
- post - 如何使用 PlayWright 进行 POST 请求
- c# - 'Microsoft.Data.SqlClient.SNINativeMethodWrapper' 的类型初始化程序引发异常
- javascript - 如何通过childNodes使用for循环?
- python - 将 data-00000-of-00001 文件转换为 Tensorflow Lite