Python 生成器和yield:如何知道程序位于哪一行
假设你有一个简单的 Python 生成器,如下所示:
更新:
def f(self):
customFunction_1(argList_1)
yield
customFunction_2(argList_2)
yield
customFunction_3(argList_3)
yield
...
我在另一个脚本中调用 f(),例如:
h=f()
while True:
try:
h.next()
sleep(2)
except KeyboardInterrupt:
##[TODO] tell the last line in f() that was executed
有没有办法可以执行上面的 [TODO] 部分?也就是说知道 f() 中在键盘中断发生之前执行的最后一行?
Suppose you have a simple generator in Python like this :
Update :
def f(self):
customFunction_1(argList_1)
yield
customFunction_2(argList_2)
yield
customFunction_3(argList_3)
yield
...
I call f() in another script like :
h=f()
while True:
try:
h.next()
sleep(2)
except KeyboardInterrupt:
##[TODO] tell the last line in f() that was executed
Is there a way that I can do the [TODO] section above? that is knowing the last line in f() that was executed before keyboardInterrupt occurred ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 enumerate() 来计数:(
因为在您的示例中
yield
不会产生值,value
当然将为 None)或者非常明确地使用详细指示:
You can use enumerate() to count:
(because in your example
yield
does not yield a value,value
will of course be None)Or very explicit using a verbose indication:
如果您想知道行号以进行调试,那么在 CPython 中您可以使用
h.gi_frame.f_lineno
。这是接下来要执行的行,索引为 1。我不确定这是否适用于 CPython 以外的 Python 实现。如果您不想出于调试目的了解这一点,那么 Remi 的
enumerate
解决方案 更加简洁。If you want to know the line number for debugging purposes then in CPython you can use
h.gi_frame.f_lineno
. This is the line which will be executed next and is 1-indexed. I'm not sure if this works on Python implementations other than CPython.If you don't want to know this for debugging purposes then Remi's
enumerate
solution is far cleaner.为什么不从 f() 中产生 i 并使用它?
Why don't you yield i from f() and use that ?
我将对
sleep()
的调用移至f
中,因为只有当异常发生在f()
内部时,这才有效。I moved the call to
sleep()
intof
as this only works if the exception happens insidef()
.