gpt4 book ai didi

python - 忽略Python异常并直接在子模块代码中继续

转载 作者:行者123 更新时间:2023-12-01 07:47:26 25 4
gpt4 key购买 nike

我使用的 python 库会抛出一个已知错误的异常。事实上,最近的拉取请求建议仅删除引发异常的行。

有没有办法强制Python代码继续忽略异常而不打破子模块代码?将库调用嵌入到 except block 中并没有帮助,因为后续代码将不会被执行。

我可以自己合并拉取请求并安装库的自定义版本,但这会破坏整个部署/依赖/更新过程。

我想忽略的代码由这两行组成:

if '<img class="icon meh" src="/yts/img' not in self.watch_html:
raise VideoUnavailable('This video is unavailable.')

来自 this file已由 this commit 修补在 this pr .

最佳答案

我认为这是不可能的,即使是这样,我相信它也只会不太可维护。

我认为在这种情况下最好的解决方案是子类化并覆盖有问题的函数。缺点是如果更新了库,就必须更新函数,直到问题完全解决。它可能看起来像这样,删除了异常行,使用您从 pytube 链接的代码:

from pytube import Caption
from pytube import CaptionQuery
from pytube import extract
from pytube import mixins
from pytube import request
from pytube import Stream
from pytube import StreamQuery
from pytube.compat import install_proxy
from pytube.compat import parse_qsl
from pytube.exceptions import VideoUnavailable
from pytube.helpers import apply_mixin

from pytube import YouTube


class MyYouTube(YouTube):
# https://github.com/nficano/pytube/blob/master/pytube/__main__.py#L150
def prefetch(self):
"""Eagerly download all necessary data.

Eagerly executes all necessary network requests so all other
operations don't does need to make calls outside of the interpreter
which blocks for long periods of time.

:rtype: None

"""
self.watch_html = request.get(url=self.watch_url)
self.embed_html = request.get(url=self.embed_url)
self.age_restricted = extract.is_age_restricted(self.watch_html)
self.vid_info_url = extract.video_info_url(
video_id=self.video_id,
watch_url=self.watch_url,
watch_html=self.watch_html,
embed_html=self.embed_html,
age_restricted=self.age_restricted,
)
self.vid_info = request.get(self.vid_info_url)
if not self.age_restricted:
self.js_url = extract.js_url(self.watch_html, self.age_restricted)
self.js = request.get(self.js_url)

#YouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download() # Doesnt work
MyYouTube('https://www.youtube.com/watch?v=irauhITDrsE').streams.first().download() # Works

根据编程语言的不同,由于可见性的原因,这可能并不总是可行。幸运的是 Python 并不关心太多。

关于python - 忽略Python异常并直接在子模块代码中继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56401725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com