[英]Python Generators and yield : How to know which line the program is at
Suppose you have a simple generator in Python like this : 假设您在Python中有一个简单的生成器,如下所示:
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 : 我在另一个脚本中调用f(),如:
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? 有没有办法让我可以做上面的[TODO]部分? that is knowing the last line in f() that was executed before keyboardInterrupt occurred ?
知道在keyboardInterrupt发生之前执行的f()中的最后一行?
You can use enumerate() to count: 您可以使用enumerate()来计算:
def f():
...
yield
...
yield
...
for step, value in enumerate(f()):
try:
time.sleep(2)
except KeyboardInterrupt:
print(step) # step holds the number of the last executed function
(because in your example yield
does not yield a value, value
will of course be None) (因为在你的例子中,
yield
不产生值, value
当然是None)
Or very explicit using a verbose indication: 或使用详细指示非常明确:
def f():
...
yield 'first function finished'
...
yield 'almost done'
...
for message in f():
try:
time.sleep(2)
except KeyboardInterrupt:
print(message)
If you want to know the line number for debugging purposes then in CPython you can use h.gi_frame.f_lineno
. 如果您想知道用于调试目的的行号,那么在CPython中您可以使用
h.gi_frame.f_lineno
。 This is the line which will be executed next and is 1-indexed. 这是接下来要执行的行并且是1索引的。 I'm not sure if this works on Python implementations other than CPython.
我不确定这是否适用于CPython以外的Python实现。
h=f()
while True:
try:
h.next()
sleep(2)
except KeyboardInterrupt:
print h.gi_frame.f_lineno - 1 # f_lineno is the line to be executed next.
If you don't want to know this for debugging purposes then Remi's enumerate
solution is far cleaner. 如果你不想知道这个用于调试目的,那么Remi的
enumerate
解决方案就更清晰了。
你为什么不从f()中产生i并使用它?
val = h.next()
def f(self):
sleep(10)
yield
sleep(10)
yield
sleep(10)
yield
h=f()
while True:
try:
h.next()
except KeyboardInterrupt:
stack_trace = sys.exc_info()[2] # first traceback points into this function where the exception was caught
stack_trace = stack_trace.tb_next # now we are pointing to where it happened (in this case)
line_no = stack_trace.tb_lineno # and here's the line number
del stack_trace # get rid of circular references
I moved the call to sleep()
into f
as this only works if the exception happens inside f()
. 我将调用
sleep()
到f
因为这只有在f()
内发生异常时才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.