繁体   English   中英

Python生成器和yield:如何知道程序所在的行

[英]Python Generators and yield : How to know which line the program is at

假设您在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]部分? 知道在keyboardInterrupt发生之前执行的f()中的最后一行?

您可以使用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

(因为在你的例子中, yield不产生值, value当然是None)

或使用详细指示非常明确:

def f():

    ...
    yield 'first function finished'
    ...
    yield 'almost done'
    ... 


for message in f():
    try:
        time.sleep(2)
    except KeyboardInterrupt:
        print(message)

如果您想知道用于调试目的的行号,那么在CPython中您可以使用h.gi_frame.f_lineno 这是接下来要执行的行并且是1索引的。 我不确定这是否适用于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.

如果你不想知道这个用于调试目的,那么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

我将调用sleep()f因为这只有在f()内发生异常时才有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM