我正在尝试在多个 pafy 实例上使用多线程来获取多个视频流。我的代码的简化版本:
import pafy
import threading
def get_playurl(url):
video = pafy.new(url)
best = video.getbest()
playurl = best.url
return playurl
threads = []
for i in range(5):
t = threading.Thread(target=get_playurl, args=("https://www.youtube.com/watch?v=erG5rgNYSdk&ab_channel=WeezerVEVO",))
t.start()
threads.append(t)
for thread in threads:
thread.join()
一些线程会成功获取 playurl,而另一些线程会引发 ImportError:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\my_name\AppData\Local\Programs\Python\Python39\Lib\threading.py", line 954, in _bootstrap_inner
self.run()
File "C:\Users\my_name\AppData\Local\Programs\Python\Python39\Lib\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\my_name\VSCodeProjects\my_project\stackoverflow_example.py", line 6, in get_playurl
video = pafy.new(url)
File "C:\Users\my_name\VSCodeProjects\my_project\.venv\lib\site-packages\pafy\pafy.py", line 122, in new
from .backend_youtube_dl import YtdlPafy as Pafy
ImportError: cannot import name 'YtdlPafy' from partially initialized module 'pafy.backend_youtube_dl' (most likely due to a circular import) (C:\Users\my_name\VSCodeProjects\my_project\.venv\lib\site-packages\pafy\backend_youtube_dl.py)
哪些成功,哪些引发异常似乎是随机的,并且每次都不同。我是线程新手,所以不确定这里的问题是什么。我没有与这些模块中的任何一个具有相同名称的任何文件,并且我还安装了 youtube-dl 依赖项 + 更新了所有其他没有任何效果的文件。
任何帮助表示赞赏:)