简体   繁体   中英

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'

I tried to read file with parser argument, somehow it didnt work..help please..

ignore for word requirement ignore for word requirement ignore for word requirement

(1) You need return 'args' in your parse_command_line() function.

(2) Your add_argment function lead to open file directly using your argument as file name.

%%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


----------

parse_command_line must return args object. Actually your parsing function returns None.

And of course None hasn't any attribute whatever it's name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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