簡體   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