tensorflow中python中with用法的理解

本文介绍了Python中的with语句,它作为上下文管理器用于资源的获取与释放,例如在TensorFlow中管理Session。通过对比try-finally结构,阐述了with-as如何简化代码,确保资源如文件、锁等在使用后会被正确关闭。同时,文章通过示例解释了__enter__和__exit__方法的工作原理,并提到了在Python 2.5及以后版本中file对象对with语句的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class tf.Session

A class for running TensorFlow operations.

Session object encapsulates the environment in which Operation objects are executed, and Tensor objects 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 variablesqueues, 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

先说明一个常见问题,文件打开:

1
2
3
4
5
6
7
try :
     f = open ( 'xxx' )
     do something
except :
     do something
finally :
     f.close()

其实我个人不止一次在网上看到有这么写的了,这个是错的。
首先正确的如下:

1
2
3
4
5
6
7
8
9
10
11
try :
     f = open ( 'xxx' )
except :
     print 'fail to open'
     exit( - 1 )
try :
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值