擅长:python、mysql、java
<p>您可以在此处定义自己的上下文管理器:</p>
<pre><code>import os
class create_temp_file(object):
def __enter__(self):
"""Define entry point actions here"""
self.filename = os.tempnam()
self.file_obj = open(self.filename, 'w')
return self.file_obj
def __exit__(self, ex_type, ex_value, ex_traceback):
"""define cleanup actions here"""
self.file_obj.close()
os.remove(self.filename)
</code></pre>
<p>现在使用<code>with</code>语句,这是python做try finally的方式</p>
^{pr2}$
<p>但是<code>os.tempnam</code>不安全,最好使用<a href="http://docs.python.org/2/library/tempfile.html#tempfile" rel="nofollow">tempfile</a>模块来做这些事情。在</p>
<blockquote>
<p>RuntimeWarning: tempnam is a potential security risk to your program</p>
</blockquote>
^{3}$
<p>如果<code>delete</code>为true(默认值),则文件一关闭即被删除(或当文件对象被垃圾回收时)</p>