Cambray
Cambray

Reputation: 134

Python ArgParse AttributeError: 'str' object has no attribute

I have implemented argparse into a Python script like so:

parser = argparse.ArgumentParser()
parser.add_argument("-s", "--shortterm", help="Tweets top information from the past month", default="track",
                    choices=choices, dest="shortterm")
parser.add_argument("-m", "--mediumterm", help="Tweets top information from the past 6 months", default="track",
                    choices=choices)
parser.add_argument("-l", "--longterm", help="Tweets top information from the past few years", default="track",
                    choices=choices)
args = parser.parse_args()

Which I then check args for things the user could have entered or selected, like so:

if args.mediumterm:
    if args.mediumterm == "all":
        get_top_tracks(medium_term)
        get_top_artists(medium_term)
    else:
        if args == "track":
            get_top_tracks(medium_term)
        elif args == "artist":
            get_top_artists(medium_term)

When I run the script with the following command:

python top_tracks_artists_spotify_time.py --mediumterm all

I get the following error:

Traceback (most recent call last):
File "top_tracks_artists_spotify_time.py", line 127, in <module>
if args.mediumterm:
AttributeError: 'str' object has no attribute 'mediumterm'

The annoying thing is running:

python top_tracks_artists_spotify_time.py --shortterm all

runs the script successfully.

EDIT: I have added dest="mediumterm" to the argparse to no avail

Upvotes: 2

Views: 8990

Answers (1)

hpaulj
hpaulj

Reputation: 231625

Your processing code, after args = parser.parse_args() should look something like:

term = args.mediumterm
if term:
    if term == "all":
        get_top_tracks(term)     # unless medium_term is defined else where
        get_top_artists(term)
    else:
        if term == "track":
            get_top_tracks(term)
        elif term == "artist":
            get_top_artists(term)

Similarly for shortterm and longterm. Once created by parse_args, args should not be reassigned (it will only confuse you and your readers).

Upvotes: 1

Related Questions