Python ArgParse AttributeError:“ str”对象没有属性

时间:2018-08-01 23:09:48

标签: python argparse

我已经将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'

烦人的事情正在运行:

python top_tracks_artists_spotify_time.py --shortterm all

成功运行脚本。

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

1 个答案:

答案 0 :(得分:1)

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不应重新分配(它只会使您和您的读者感到困惑)。