python parser read_file() AttributeError: 'NoneType' object has no attribute 'infile'

python parser read_file() AttributeError: 'NoneType' object has no attribute 'infile'

%%writefile testcipher.py
import argparse
def parse_command_line():
    parser=argparse.ArgumentParser()
    parser.add_argument("infile",type=argparse.FileType('r'),help="show this help message and exit")
    args=parser.parse_args()

def read_file(file_path):
    with open(file_path,"r") as f:
        message=f.read()
    return message
args = parse_command_line()
read_file(args.infile)

----------

%%bash

python3 testcipher.py plain_message.txt


----------

Traceback (most recent call last):
  File "testcipher.py", line 13, in <module>
    read_file(args.infile)
AttributeError: 'NoneType' object has no attribute 'infile'

我尝试使用解析器参数读取文件,但不知何故它不起作用..求助..

忽略单词要求忽略单词要求忽略单词要求

parse_command_line 必须 return args 对象。其实你的解析函数 returns None.

当然 None 没有任何属性,不管它叫什么名字。

(1) 您的 parse_command_line() 函数中需要 return 'args'。

(2) 您的 add_argment 函数导致直接使用您的参数作为文件名打开文件。

%%writefile testcipher.py

import argparse
def parse_command_line():
    parser=argparse.ArgumentParser()
    parser.add_argument("infile",type=str,help="show this help message and exit")
    args=parser.parse_args()
    return args

def read_file(file_name):
    __file = open(file_name)
    message=__file.read()
    return message

args = parse_command_line()
message = read_file(args.infile)
print (message)

----------

%%bash

python3 testcipher.py plain_message.txt


----------