If 语句不能正常工作,除非我使用调试器逐步执行它。使用 pytube
If statement does not work properly unless I use a debugger to step through it. Using pytube
我正在使用 pytube 将肯定是 link 的 url 转换为 YouTube 播放列表 pytube.Playlist()
if "/playlist?list=" in url:
playlist = Playlist(url)
if len(playlist.video_urls._elements) == 0:
print("Some error message")
问题是我用来测试的播放列表中有大约 300 个视频,所以应该跳过这个 if
语句,但它会进入其中并打印错误消息。所以很自然地,我用调试器检查了它,出于某种原因,一旦我开始单步执行代码,它就会按应有的方式工作并跳过 if
语句。
有人知道可能是什么问题吗?
IDE: Visual Studio 代码
OS: Windows 10
Playlist.video_urls
is a DeferredGeneratorList
,不是列表。因此,在您对其进行迭代之前,它没有长度。
@property # type: ignore
@cache
def video_urls(self) -> DeferredGeneratorList:
"""Complete links of all the videos in playlist
:rtype: List[str]
:returns: List of video URLs
"""
return DeferredGeneratorList(self.url_generator())
此外,您正在检查 class/API 私有的 _elements
的长度。它是 initialised to an empty list,所以它的长度最初始终为零。
因此,要么在 playlist.video_urls
上调用 len()
或更好,使用提供的方法填充列表 generate_all()
或仅在其上调用 list()
。
它在你的调试器中工作的原因是调试器试图访问列表的元素来找到它的长度,这会触发迭代并填充它。
你真好,至少尝试了调试器并注意到正常执行与调试器执行的行为差异! +1
而不是检查长度,只是迭代它并检查是否有任何事情已经完成,带有标志值:
if "/playlist?list=" in url:
playlist = Playlist(url)
had_videos = False # initial value
for video in playlist.video_urls:
had_videos = True # if exec gets here, you had at least one vid
# do something with each `video`
if not had_videos:
print("Some error message")
我正在使用 pytube 将肯定是 link 的 url 转换为 YouTube 播放列表 pytube.Playlist()
if "/playlist?list=" in url:
playlist = Playlist(url)
if len(playlist.video_urls._elements) == 0:
print("Some error message")
问题是我用来测试的播放列表中有大约 300 个视频,所以应该跳过这个 if
语句,但它会进入其中并打印错误消息。所以很自然地,我用调试器检查了它,出于某种原因,一旦我开始单步执行代码,它就会按应有的方式工作并跳过 if
语句。
有人知道可能是什么问题吗?
IDE: Visual Studio 代码
OS: Windows 10
Playlist.video_urls
is a DeferredGeneratorList
,不是列表。因此,在您对其进行迭代之前,它没有长度。
@property # type: ignore
@cache
def video_urls(self) -> DeferredGeneratorList:
"""Complete links of all the videos in playlist
:rtype: List[str]
:returns: List of video URLs
"""
return DeferredGeneratorList(self.url_generator())
此外,您正在检查 class/API 私有的 _elements
的长度。它是 initialised to an empty list,所以它的长度最初始终为零。
因此,要么在 playlist.video_urls
上调用 len()
或更好,使用提供的方法填充列表 generate_all()
或仅在其上调用 list()
。
它在你的调试器中工作的原因是调试器试图访问列表的元素来找到它的长度,这会触发迭代并填充它。
你真好,至少尝试了调试器并注意到正常执行与调试器执行的行为差异! +1
而不是检查长度,只是迭代它并检查是否有任何事情已经完成,带有标志值:
if "/playlist?list=" in url:
playlist = Playlist(url)
had_videos = False # initial value
for video in playlist.video_urls:
had_videos = True # if exec gets here, you had at least one vid
# do something with each `video`
if not had_videos:
print("Some error message")