Python“ with”语句:__exit __()被忽略

特蕾莎修女和少年

考虑到这个小的Python类,每当我用Ctrl+停止脚本时C,该__exit__函数都会在引发异常之前运行:

import time


class MyClass(object):
    def __init__(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('------ cleanup ------')


with MyClass():
    time.sleep(100)

跑步:

$ python3 test.py 
^C------ cleanup ------
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    time.sleep(100)
KeyboardInterrupt

在子类Chrome WebDriver的类似代码中,为什么我的清理功能被忽略了?

import selenium
from selenium.webdriver.common.by import By


class WebDriver(selenium.webdriver.Chrome):
    def __init__(self, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = url

    def __enter__(self):
        self.get(self.url)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('------ cleanup ------')


with WebDriver('https://google.com') as driver:
    driver.find_element(By.ID, 'lst-ib').send_keys('Search')

跑步:

$ python3 test2.py 
^CTraceback (most recent call last):
  File "test2.py", line 19, in <module>
    with WebDriver('https://google.com') as driver:
  File "test2.py", line 9, in __init__
    super().__init__(*args, **kwargs)
  File "/vagrant/app/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
    self.service.start()
  File "/vagrant/app/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 90, in start
    time.sleep(1)
KeyboardInterrupt

但是,使用try: ... finally:语句强制执行此操作是可行的

try:
    with WebDriver('https://google.com') as driver:
        driver.find_element(By.ID, 'lst-ib').send_keys('Search')
finally:
    print('------ cleanup ------')

跑步:

^C------ cleanup ------
Traceback (most recent call last):
  File "test2.py", line 20, in <module>
    with WebDriver('https://google.com') as driver:
  File "test2.py", line 9, in __init__
    super().__init__(*args, **kwargs)
  File "/vagrant/app/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
    self.service.start()
  File "/vagrant/app/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 90, in start
    time.sleep(1)
KeyboardInterrupt
杰森·哈珀(Jasonharper)

注意,回溯表明您仍在WebDriver对象的__init __()中-换句话说,with语句尚未执行,Python仍在评估其参数。我不确定确切的规则,但是我很确定,如果尚未调用__enter __(),永远不会调用__exit __()。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章