Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: "AttributeError: 'Namespace' object has no attribute" argparse

Tags:

python

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?

like image 662
David Botezatu Avatar asked Dec 24 '22 12:12

David Botezatu


1 Answers

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.

like image 61
DeepSpace Avatar answered Feb 08 '23 22:02

DeepSpace