python parser read_file()AttributeError:'NoneType'对象没有属性'infile'

问题描述 投票:0回答:2
%%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'

我试图用解析器参数读取文件,不知何故它没有工作..请帮助..

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

python-3.x parsing readfile
2个回答
1
投票

(1)您需要在parse_command_line()函数中返回'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


----------

0
投票

parse_command_line必须返回args对象。实际上你的解析函数返回None。

当然,无论它的名字是什么都没有任何属性。

© www.soinside.com 2019 - 2024. All rights reserved.