gpt4 book ai didi

Python "with"语句 : __exit__() ignored

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:46 24 4
gpt4 key购买 nike

考虑到这个小的 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

最佳答案

请注意,回溯显示您仍在 WebDriver 对象的 __init__() 中 - 换句话说,with 语句尚未执行,Python 仍在评估其参数。我不确定确切的规则,但我很确定如果 __enter__() 尚未被调用,则 __exit__() 将永远不会被调用。

关于Python "with"语句 : __exit__() ignored,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428025/

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