我已经将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中,但无济于事
答案 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)
与shortterm
和longterm
类似。由parse_args
创建后,args
不应重新分配(它只会使您和您的读者感到困惑)。