简体   繁体   English

python有自动资源管理吗?

[英]Does python have automatic resource management?

All versions of Java require the user to close resources manually - usually handled in the finally block. 所有版本的Java都要求用户手动关闭资源 - 通常在finally块中处理。 Java 7 is about to get ARM (automatic resource management) blocks. Java 7即将获得ARM (自动资源管理)块。

  1. Firstly I don't see a finally block concept in python. 首先,我没有在python中看到finally块概念。 Or do you close resources in the catch for each raised exceptions ? 或者,您是否为每个引发的异常关闭了catch中的资源?
  2. Is there a library that performs ARM in python ? 是否有一个在python中执行ARM的库? If not, then what is the pythonic way to do ARM ? 如果没有,那么做pyms的pythonic方法是什么?

There is a try: except: finally: in python. 有一个尝试:除了:最后:在python中。

You can also use the with: statement, which I believe is what you are after for ARM. 你也可以使用with:语句,我相信你所追求的是ARM。 These are called context managers. 这些被称为上下文管理器。 http://www.python.org/dev/peps/pep-0343/ http://www.python.org/dev/peps/pep-0343/

There is some automated resource management in Python. Python中有一些自动化资源管理。 Most objects who open resources will close them when they get garbage collected. 打开资源的大多数对象在收集垃圾时会关闭它们。 When that happens is undefined, and it may not happen at all, so this only works if you don't use very many resources, don't care if they are open long and the resources will be closed by the operating system when the program exits. 如果发生这种情况是未定义的,并且它可能根本不会发生,所以这只有在您不使用很多资源时才会起作用,不关心它们是否打开很长时间并且当程序时操作系统将关闭资源退出。

Otherwise, use context managers and the with statement as per Matthews answer. 否则,根据Matthews的答案使用上下文管理器和with语句。

Here is a simple example that redirects stdout: 这是一个重定向stdout的简单示例:

>>> import sys
>>> class redirect_stdout:
...     def __init__(self, target):
...         self.stdout = sys.stdout
...         self.target = target
...
...     def __enter__(self):
...         sys.stdout = self.target
...
...     def __exit__(self, type, value, tb):
...         sys.stdout = self.stdout
...
>>> from StringIO import StringIO
>>> out = StringIO()
>>> with redirect_stdout(out):
...     print 'Test'
...
>>> out.getvalue() == 'Test\n'
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM