[英]Python: “AttributeError: 'Namespace' object has no attribute” argparse
[英]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'
烦人的事情正在运行:
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)
shortterm
和longterm
同样。 一旦由parse_args
创建, parse_args
不应重新分配args
(它只会使您和您的读者感到困惑)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.