首页 > 解决方案 > 对 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”会出现此错误?

标签: pythonpython-3.xargparse

解决方案


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.


推荐阅读