我试图运行此脚本,但遇到语法错误。如果我在命令行上一个接一个地添加参数,它就可以工作了。但我正试图从.txt文件中提取完整的参数列表。我怎样才能做到这一点?
谢谢
import logging
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import spotipy.util as util
logger = logging.getLogger('examples.add_tracks_to_playlist')
logging.basicConfig(level='DEBUG')
scope = 'playlist-modify-public,playlist-modify-private'
token = util.prompt_for_user_token(scope, client_id='ID',client_secret='SECRET',redirect_uri='REDIRECTURI')
def get_args():
parser = argparse.ArgumentParser(description='Adds track to user playlist')
parser.add_argument('/Users/myname/Desktop/newtracks.txt', type=argparse.FileType('r'), action='append', #changed from '-t','--tids'
required=True, help='Track ids')
parser.add_argument('-p', '--playlist', required=True,
help='Playlist to add track to')
return parser.parse_args()
def main():
args = get_args()
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id='ID',
client_secret='SECRET',
redirect_uri='REDIRECTURI',
scope=scope))
sp.playlist_add_items(args.playlist, args.'/Users/myname/Desktop/newtracks.txt')
if __name__ == '__main__':
main()
让我们测试代码的argparse
部分
In [1]: import argparse
In [2]: parser = argparse.ArgumentParser(description='Adds track to user playlist')
...: parser.add_argument('/Users/myname/Desktop/newtracks.txt', type=argparse.FileType('r'),
...: action='append', #changed from '-t','--tids'
...: required=True, help='Track ids')
...: parser.add_argument('-p', '--playlist', required=True,
...: help='Playlist to add track to')
...:
Traceback (most recent call last):
Input In [2] in <module>
parser.add_argument('/Users/myname/Desktop/newtracks.txt', type=argparse.FileType('r'), action='append', #changed from '-t','--tids'
File /usr/lib/python3.8/argparse.py:1362 in add_argument
kwargs = self._get_positional_kwargs(*args, **kwargs)
File /usr/lib/python3.8/argparse.py:1478 in _get_positional_kwargs
raise TypeError(msg)
TypeError: 'required' is an invalid argument for positionals
所以第一个错误-你指定了";"必需";具有CCD_ 2自变量。这样的论点总是必要的。让我们删除:
In [3]: parser = argparse.ArgumentParser(description='Adds track to user playlist')
...: parser.add_argument('/Users/myname/Desktop/newtracks.txt', type=argparse.FileType('r'),
...: action='append', #changed from '-t','--tids'
...: help='Track ids')
...: parser.add_argument('-p', '--playlist', required=True,
...: help='Playlist to add track to')
...:
运行时不带任何参数字符串-需要两个:
In [4]: args = parser.parse_args([])
usage: ipython3 [-h] -p PLAYLIST /Users/myname/Desktop/newtracks.txt
ipython3: error: the following arguments are required: /Users/myname/Desktop/newtracks.txt, -p/--playlist
好的,让我们指定两个必需的值-一个位置值和一个标记值:
In [6]: args = parser.parse_args(['args.txt', '-p', 'foo'])
并查看生成的args
名称空间:
In [7]: print(args)
Namespace(playlist='foo', **{'/Users/myname/Desktop/newtracks.txt': [<_io.TextIOWrapper name='args.txt' mode='r' encoding='UTF-8'>]})
让我们尝试访问其中一个属性:
In [8]: args.'/Users/myname/Desktop/newtracks.txt'
Input In [8]
args.'/Users/myname/Desktop/newtracks.txt'
^
SyntaxError: invalid syntax
不能使用这样的字符串作为属性名称。相反,您必须使用getattr
方法:
In [9]: getattr(args,'/Users/myname/Desktop/newtracks.txt')
Out[9]: [<_io.TextIOWrapper name='args.txt' mode='r' encoding='UTF-8'>]
请注意,这是一个包含已打开文件的列表。我们可以";读取";it:
In [11]: getattr(args, "/Users/myname/Desktop/newtracks.txt")[0].read()
Out[11]: 'args.txtn--foon2n--barn2n'
为什么[9]是列表-因为action='append'. 'append' doesn't make sense with a
位置, since it can't be repeated. A
位置"只能使用一次"。
现在让我们关闭这个文件:
In [13]: getattr(args, "/Users/myname/Desktop/newtracks.txt")[0].close()
使用以前使用的标志制作一个新的解析器:
parser = argparse.ArgumentParser(description='Adds track to user playlist')
parser.add_argument('-t','--tids', type=argparse.FileType('r'),
help='Track ids')
parser.add_argument('-p', '--playlist',
help='Playlist to add track to')
现在我们可以很容易地解析一些输入并查看-t
文件:
In [14]: args = parser.parse_args(['-t','args.txt', '-p', 'foo'])
In [15]: args
Out[15]: Namespace(playlist='foo', tids=<_io.TextIOWrapper name='args.txt' mode='r' encoding='UTF-8'>)
In [16]: args.tids
Out[16]: <_io.TextIOWrapper name='args.txt' mode='r' encoding='UTF-8'>
In [17]: args.tids.read()
Out[17]: 'args.txtn--foon2n--barn2n'
In [18]: args.close()