通过argparse命令行读取csv文件时出错



我将使用'argparse'来读取类似命令的参数及其对应的字符串:

sample_script_2

"""Spreadsheet Column Printer
testing
"""
import argparse
import pandas as pd
def get_spreadsheet_cols(file_loc, print_cols=False):

file_data = pd.read_csv(file_loc)
col_headers = list(file_data.columns.values)
if print_cols:
print("n".join(col_headers))
return col_headers
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-input_file", type=argparse.FileType('r'), help='reading csv file')
args = parser.parse_args()
get_spreadsheet_cols(args.input_file, print_cols=True)
if __name__ == "__main__":
main()

当我以以下方式执行此文件时,它运行良好:

$ python3 sample_script_2.py -input_file test.csv
name
address
Salary
$ python3 sample_script_2.py -h
usage: sample_script_2.py [-h] [-input_file INPUT_FILE]
Testing
optional arguments:
-h, --help            show this help message and exit
-input_file INPUT_FILE
reading csv file

然而,当我做以下事情时,就是开始给我错误:

$ python3 sample_script_2.py
Traceback (most recent call last):
File "test_area/sample_script_2.py", line 52, in <module>
main()
File "test_area/sample_script_2.py", line 49, in main
get_spreadsheet_cols(args.input_file, print_cols=True)
File "test_area/sample_script_2.py", line 38, in get_spreadsheet_cols
file_data = pd.read_csv(file_loc)
File "/opt/user/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "/opt//user/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 586, in read_csv
return _read(filepath_or_buffer, kwds)
File "/opt/user/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 482, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/opt//user/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 811, in __init__
self._engine = self._make_engine(self.engine)
File "/opt//user/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1040, in _make_engine
return mapping[engine](self.f, **self.options)  # type: ignore[call-arg]
File "/opt//user/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 51, in __init__
self._open_handles(src, kwds)
File "/opt//user/lib/python3.9/site-packages/pandas/io/parsers/base_parser.py", line 222, in _open_handles
self.handles = get_handle(
File "/opt//user/lib/python3.9/site-packages/pandas/io/common.py", line 609, in get_handle
ioargs = _get_filepath_or_buffer(
File "/opt//user/lib/python3.9/site-packages/pandas/io/common.py", line 396, in _get_filepath_or_buffer
raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class 'NoneType'>

令人惊讶的是,如果我在sample_script_2.py:中的此行中将"-input_file"更改为"input_file",错误就会消失

-->   parser.add_argument("input_file", type=argparse.FileType('r'), help='reading csv file')
$ python3 sample_script_2.py
usage: sample_script_2.py [-h] input_file
sample_script_2.py: error: the following arguments are required: input_file

在脚本中使用"-input_file"时,如何消除错误?

当您查找未提供的参数时,模块argparse将不返回任何值。错误Invalid file path or buffer object type: <class 'NoneType'>意味着None不能指向文件(或其内容(。但是,当您使用input_file而不是-input_file时,argparse认为这是一个必需的参数,并退出程序,返回错误1。

argparse的代码中,它是这样说的:if no positional args are supplied or only one is supplied and it doesn't look like an option string, parse a positional argument。并且它通过使用prefix_chars(默认为'-'(来实现。因此,参数-input_file被解析为可选参数,并且默认为None。而当它是一个位置参数时,如果没有提供,它将退出并返回错误1。

所以你的问题的答案是:i( 您想要使用argparse的现有功能:除非您将其定位(必需(,否则这是不可能的。ii(您可以使用此程序的特定实现:尝试此

import argparse
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-input_file", type=argparse.FileType('r'), help='reading csv file')
args = parser.parse_args()
if args.input_file == None:
parser.print_help() # or print_usage based on your choice
parser.error("You should supply the input file")
else:
get_spreadsheet_cols(args.input_file, print_cols=True)

然而,当有太多争论时,这会变得一团糟

最新更新