简体   繁体   English

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

[英]Error while reading csv file via argparse command line

I am getting to use ' argparse ' for reading the command like arguments along with their corresponding string:我开始使用“ argparse ”来读取命令之类的参数及其相应的字符串:

sample_script_2示例脚本_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()

when I execute this file following way, it runs fine:当我按照以下方式执行此文件时,它运行良好:

$ 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

However, is start giving me error when I do following:但是,当我执行以下操作时开始给我错误:

$ 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'>

Surprisingly, the error disappear, if I change '-input_file' to 'input_file' in this line in sample_script_2.py:令人惊讶的是,如果我在 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

How could I get rid of the error while using the '-input_file' in my script?在我的脚本中使用“-input_file”时如何摆脱错误?

The module argparse returns none when you are looking for an argument that's not supplied.当您查找未提供的参数时,模块argparse将返回 none。 And the error Invalid file path or buffer object type: <class 'NoneType'> means None can't point to a file(or its content).并且错误Invalid file path or buffer object type: <class 'NoneType'>表示None不能指向文件(或其内容)。 But when you use input_file instead of -input_file , argparse thinks it's a required parameter and exits the program with error 1 for you.但是当您使用input_file而不是-input_file时, argparse认为它是必需的参数并为您退出程序并显示错误 1。

In the code of argparse , it says this: if no positional args are supplied or only one is supplied and it doesn't look like an option string, parse a positional argument .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 And it does so by using prefix_chars (defaults to '-' ).它通过使用prefix_chars (默认为'-' )来实现。 Thus the argument -input_file is parsed as an optional one and defaults to None.因此,参数-input_file被解析为可选参数,默认为 None。 Whereas when it's a positional argument, it exits with error 1 if not supplied.而当它是一个位置参数时,如果没有提供,它会以错误 1 ​​退出。

So the answer to your question is: this is impossible unless you make it positional(required).因此,您的问题的答案是:除非您将其设置为位置(必需),否则这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM