Python ArgParse AttributeError: 'str' object has no attribute

Python ArgParse AttributeError: 'str' object has no attribute

我已经将 argparse 实现到 Python 脚本中,如下所示:

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()

然后我检查 args 以了解用户可能输入或选择的内容,如下所示:

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)

当我运行脚本使用以下命令时:

python top_tracks_artists_spotify_time.py --mediumterm all

我收到以下错误:

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'

烦人的是运行ning:

python top_tracks_artists_spotify_time.py --shortterm all

运行脚本成功。

编辑:我已将 dest="mediumterm" 添加到 argparse 中但无济于事

您的处理代码,在 args = parser.parse_args() 之后应该类似于:

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)

shorttermlongterm 类似。一旦由 parse_args 创建,args 不应重新分配(这只会让您和您的读者感到困惑)。