tensorflow中python中with用法的理解
2016-11-08 14:50
579 查看
class tf.Session
A class for running TensorFlow operations.A
Sessionobject encapsulates the environment in which
Operationobjects
are executed, and
Tensorobjects are evaluated. For example:
# Build a graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # Launch the graph in a session. sess = tf.Session() # Evaluate the tensor `c`. print(sess.run(c))
A session may own resources, such as variables, queues,
and readers.
It is important to release these resources when they are no longer required. To do this, either invoke the
close()method
on the session, or use the session as a context manager. The following two examples are equivalent:
# Using the `close()` method. sess = tf.Session() sess.run(...) sess.close() # Using the context manager. with tf.Session() as sess: sess.run(...)
因此根据这个用法我去search到了如下python中的with-as statement(也称context manager),学习了一番,收获颇丰,参考到好的资料并理解为什么,在此分享。
reference:http://zhoutall.com/archives/325
先说明一个常见问题,文件打开:
首先正确的如下:
我们为什么要写finally,是因为防止程序抛出异常最后不能关闭文件,但是需要关闭文件有一个前提就是文件已经打开了。
在第一段错误代码中,如果异常发生在f=open(‘xxx’)的时候,比如文件不存在,立马就可以知道执行f.close()是没有意义的。改正后的解决方案就是第二段代码。
好了言归正转,开始讨论with语法。
首先我们从下面这个问题谈起,try-finally的语法结构:
set things up就表示
f=open('xxx'),
tear things down就表示
f.close()。在比如像多线程锁,资源请求,最终都有一个释放的需求。Try…finally结构保证了tear things down这一段永远都会执行,即使上面do something得工作没有完全执行。
如果经常用这种结构,我们首先可以采取一个较为优雅的办法,封装!
另一个办法是使用生成器,但是只需要生成一次数据,我们用for-in结构去调用他:
最终的python-dev团队的解决方案。(python 2.5以后增加了with表达式的语法)
另外,__exit__除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。下面的样例代码跳过了所有的TypeError,而让其他异常正常抛出。
感谢以下参考资料:
stackoverflow:
Catching an exception while using a Python ‘with’ statement
Understanding
Python’s “with” statement
python docs:
http://docs.python.org/2/reference/compound_stmts.html#with
http://docs.python.org/2/reference/datamodel.html#context-managers
http://docs.python.org/2/library/contextlib.html#contextlib.nested
相关文章推荐
- tensorflow中python中with用法的理解
- Python的with用法理解
- js with理解和用法
- python with用法
- python 中关于with...as的用法
- Python开发——理解With语句
- 理解Python的With语句
- JS with理解和用法
- Python with的用法
- Python with语句用法
- 理解Python的With语句
- 理解Python的With语句
- monkeyrunner其他测试例子收集,便于理解python一些基本用法
- python学习:异常处理、with用法以及utf8中文显示
- 【原创翻译】理解python的with语句
- Python 中的with语句用法
- python with...as...用法
- python中关于with及contextlib的用法
- python中关于with及contextlib的用法
- 理解Python的With语句