简体   繁体   中英

Python: “AttributeError: 'Namespace' object has no attribute” argparse

My code looks like this:

parser.add_argument('-i', '--input', help='Input path/to/file.csv', required=True)
parser.add_argument('-oh', '--output-html', help='Output path/to/confusion_matrix.html', required=True)
parser.add_argument('-oc', '--output-csv', help='Output path/to/confusion_matrix.csv', required=True)
args = parser.parse_args()

....

y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")
df_confusion = pd.crosstab(y_true, y_pred)
df_confusion.to_html(args.output-html)
df_confusion.to_csv(args.output-csv)

When i try to run it, it gives me this error:

df_confusion.to_html(args.output-html)
AttributeError: 'Namespace' object has no attribute 'output'

However, if i change from

df_confusion.to_html(args.output-html)

To

df_confusion.to_html(args.output)

It works as it should. Can anyone explain why it doesn't work, and how can i make it work with args.output-html?

By default (ie if you don't provide dest kwarg to add_argument ) it changes - to _ when creating the attribute since Python attributes can't contain the character - (as a matter of fact they can, but then they are only accessible by using getattr ).

It means that you should change args.output-html to args.output_html , and args.output-csv to args.output_csv .

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