【Python利用上下文实现类似with open功能】教程文章相关的互联网学习教程文章

Python上下文管理器的使用【代码】

上下文管理器可以控制代码块执行前的准备动作,以及执行后的清理动作。 创建一个上下文管理器类的步骤:(1)一个__init__方法,来完成初始化(可选)(2)一个__enter__方法,来完成所有建立工作(3)一个__exit__方法,来完成所有清理工作 例子1:class User():def __init__(self):print(实例化)def __enter__(self):print(进入)def __exit__(self, exc_type, exc_val, exc_trace):print(退出)obj = User() with obj:print(主要内容...

python super() – __new__ 上下文中的两个参数版本【代码】

参见英文答案 > what does `super()` in `__new__` 3个我已多次阅读the documentation for super()但仍然没有得到两个参数版本返回的内容.Return a proxy object that delegates method calls to a parent orsibling class of type. This is useful for accessing inherited methodsthat have been overridden in a class.>什么是代理对象?>父母还是兄弟姐妹?If the second argument is an o...

Python Day 51 浅淡python中with的用法,上下文管理器【代码】【图】

#案例一class Foo(object):def __init__(self):print(实例化一个对象)def __enter__(self):print(进入)def __exit__(self, exc_type, exc_val, exc_tb):print(退出)obj = Foo()with obj:print(正在执行)#上面代码执行结果为: 实例化一个对象 进入 正在执行 退出#结论 我们知道,实例化Foo,得到obj对象,会执行Foo的__init__方法,也就是打印了第一句; 按照,程序从上至下执行,应该会打印“正在执行”才对,为什么会在它之前先打...

python – 有没有办法将上下文管理器中的源代码作为字符串?【代码】

使用inspect.getsourcelines(func)函数接收函数can be的源代码.有没有办法为上下文管理器做同样的事情?with test():print('123')# How to get "print('123')" as line here?解决方法:您对此解决方案有何看法?import tracebackclass ContextManagerContent(object):def __enter__(self):returndef __exit__(self, _type, value, _traceback):stack = traceback.extract_stack()f, last_line = self._get_origin_info(stack)with o...

python – 如何在BeautifulSoup中获取搜索的上下文?【代码】

我正在解析由各种HTML实体组成的网页,其中包括以下片段:<p style="text-align: center;"><img src="http://example.com/smthg.png" alt="thealtttext" /></p> <p style="text-align: center;"><strong>My keywords : <a href="http://example.com/hello.html" target="_blank"> some text </a> </strong></p> <p style="text-align: center;"><strong>some other words : <a href="http://example.com/anotherlink.html" target="...

python – 在QTreeWidget中调用上下文菜单【代码】

当用户点击QTreeWidgetItem中的对象时,我想弹出一个菜单.我虽然从QWidget捕获信号contextMenuRequested,然后使用itemAt从视图中检索索引.但这看起来不太漂亮.有没有更简单的方法可以调用视图中的项目菜单?解决方法:编写自己的自定义ItemDelegate并处理QAbstractItemDelegate :: editorEvent中的click事件.您可以从QModelIndex中检索单元格中的数据.在C中它看起来像这样:class ItemDelegate: public QItemDelegate { public:ItemD...

在“with”中嵌入Python上下文管理器的迭代器

我有一个返回上下文管理器的迭代器. 我想要一个pythonic with语句,它模拟几个嵌套语句的行为,一个用于迭代器返回的每个上下文管理器. 可以说,我想要(不推荐使用)contextlib.nested函数的推广.解决方法:从docs:Developers that need to support nesting of a variable number of context managers can either use the warnings module to suppress the DeprecationWarning raised by [contextlib.nested] or else use this functio...

python – 使用’yield’进行上下文切换【代码】

我正在阅读gevent教程并看到了这个有趣的片段:import geventdef foo():print('Running in foo')gevent.sleep(0)print('Explicit context switch to foo again')def bar():print('Explicit context to bar')gevent.sleep(0)print('Implicit context switch back to bar')gevent.joinall([gevent.spawn(foo),gevent.spawn(bar), ])执行流程就像这个foo – >吧 – > foo – >吧.如果没有gevent模块但是使用yield语句,是不是可以做同...

python – 在beautifulsoup的上下文中lxml和html5lib之间的区别【代码】

在beautifulsoup的上下文中,lxml和html5lib解析器的功能有区别吗?我正在尝试学习使用BS4并使用以下代码构造 – ret = requests.get('http://www.olivegarden.com') soup = BeautifulSoup(ret.text, 'html5lib') for item in soup.find_all('a'): print item['href']我开始使用lxml作为解析器,但注意到对于某些网站,即使页面中有有效链接,也永远不会输入for循环.同一页面适用于html5ib解析器.是否有任何特定类型的页面可能无法与lx...

在Python2.7上下文管理器类中处理异常的正确方法【代码】

我正在为一个正在研究的项目提供几个上下文管理器.它即将发货,我遇到了一些我开始恐慌的事情. 我的印象是你不应该再加上作为上下文管理器类的__exit__方法的参数传递的异常.但是,我正在进行一些测试,看起来上下文管理器正在抑制一个被抛入其中的异常.当我将__exit__方法更改为如下所示时:def __exit__(self, type_, value, trace):if trace is not None:print('ERROR IN TRACEBACK: ' + str(value))# PYTHON 2.7 RAISE SYNTAX:rai...

python – 使用三引号在非标准上下文中创建“docstrings”是一个好习惯吗?【代码】

我正在看某人的代码,这些代码在所有地方都有这种“docstrings”:SLEEP_TIME_ON_FAILURE = 5 """Time to keep the connection open in case of failure."""SOCKET_TIMEOUT = 15 """Socket timeout for inherited socket."""...根据Python文档,docstrings仅适用于模块,类或方法的开头. 上述非标准做法的含义是什么?为什么Python允许这个?这不会对性能产生影响吗?解决方法:就Python而言,这些不是文档字符串.它们只是用作表达式语句...

python – PySide Qt tr()不翻译,translate()做 – 上下文错误?【代码】

我想使用QTranslator来使用英文文本标签,并且仍然有软件显示德国标签. 不幸的是我的应用程序没有翻译,除非我指定上下文.以下静态函数实例化QApplication并添加所需的转换器. 第一次打印将’Apple2’正确翻译为’Apfel2′. Qt Linguist中的上下文也有上下文’app’.第二次打印虽然没有翻译.类中的tr()调用(在同一个python文件中定义)也不转换.def load_application():app = QApplication()qt_translator = QTranslator()qt_translat...

保存设备上下文绘制的图像,wxPython【代码】

我需要能够保存设备上下文画布状态的图像(格式无关紧要).我尝试了dc.GetAsBitmap,但它返回了无效的位图.我该怎么做?解决方法:我相信这应该可以解决问题:def saveSnapshot(dcSource):# based largely on code posted to wxpython-users by Andrea Gavana 2006-11-08size = dcSource.Size# Create a Bitmap that will later on hold the screenshot image# Note that the Bitmap must have a size big enough to hold the screensh...

python – 如何__enter__ n上下文管理器?【代码】

使用with语句,我们可以只使用一个级别的缩进/嵌套来输入许多上下文处理程序:>>> from contextlib import contextmanager >>> @contextmanager ... def frobnicate(n): ... print('frobbing {}'.format(n)) ... yield ... >>> frob1 = frobnicate(1) >>> frob2 = frobnicate(2) >>> with frob1, frob2: ... pass ... frobbing 1 frobbing 2但这似乎不起作用:>>> frobs = [frobnicate(1), frobnicate(2)] >>> with *...

python – with语句中的条件或可选上下文管理器【代码】

假设我有一些我正在使用的上下文管理器(来自第三方库):with freeze_time(test_dt):lines_of_code_1lines_of_code_2lines_of_code_3但是,假设如果test_dt没有值,则上下文管理器不应该运行,但是所有剩余的代码都应该运行,如下所示:if test_dt:with freeze_time(test_dt):lines_of_code_1lines_of_code_2lines_of_code_3 else:lines_of_code_1lines_of_code_2lines_of_code_3假设这里的lines_of_code是2-3行完全相同的代码,是否有更...

功能 - 相关标签