Python 对argparse感到困惑
我在理解argparse的工作原理时遇到了一些困难,我已经仔细阅读了文档,但理解起来仍然有一些困难Python 对argparse感到困惑,python,python-3.x,argparse,Python,Python 3.x,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", requ
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'
回溯(最近一次呼叫最后一次):
文件“\csv\u split.py”,第95行,在
参数=参数()
文件“\csv\u split.py”,第33行,参数中
是否有效\u csv(解析器,args.input\u文件,args.row\u限制)
AttributeError:“命名空间”对象没有属性“行限制”
为什么删除“-row limit”会给我带来这个错误?
args=parser.parse_args()
实际上为每个解析器的命名空间args
添加了一个属性。add_argument
调用。属性的名称是从参数名称生成的,在这里,--row limit
被转换为row\u limit
,因为变量名称中不能有破折号。有关详细信息,请参阅
因此,当您调用
parser.add_参数(…,“--row limit”,…)
时,一旦调用parse_args()
,它就会创建args.row_limit
。如前所述,稍后在代码中使用args.row\u limit
。但是如果从解析器中删除--row limit
参数,属性row\u limit
将不存在于args
中,您会想知道为什么删除参数时它不再存在?在中,csv(解析器,args.input\u文件,args.row\u limit)
中,您使用的是args.row\u limit
。若你们不解析它,它就不会存在于args
中,访问它会产生一个错误。解析后打印args
,这样你们就可以清楚地知道解析器已经完成了什么。现在完全有意义了,谢谢Carsten和Amadan!