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

时间:2019-05-31 21:05:47

标签: python exception

我使用了一个python库,该库抛出一个已知为错误的异常。实际上,最近的请求请求建议只删除引发异常的行。

是否有一种方法可以强制python代码继续忽略异常而不会破坏子模块代码?将库调用嵌入到except块中无济于事,因为不会执行后续代码。

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

我要忽略的代码由以下两行组成:

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

来自this filethis commit中被this pr修补的。

1 个答案:

答案 0 :(得分:0)

我认为在这种情况下,最好的解决方案是继承并覆盖有问题的函数。缺点是,如果更新库,则还必须更新函数,直到问题完全解决为止。 看起来像这样,使用从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并不在乎。