python 函数中的一段代码在调用者执行完毕后如何执行?

How to execute a piece of code in a python function after the caller has finished executing?

我有一个情况可以这样简化:

def caller(func):
    print('''
            This is the caller function.
            After completing execution of this function, do the JOB(see below)
            ''')
    print(*func())

def my_func():
    for i in range(5):
        yield i

    # JOB:
    print('''
            This text needs to be printed
            after everything from the caller function
            (text and numbers both) is printed
            ''')

caller(my_func)

它打印的内容:

        This is the caller function.
        After completing execution of this function, do the JOB(see below)
        

        This text needs to be printed
        after everything from the caller function
        (text and numbers both) is printed

         0 1 2 3 4

我想要的:

        This is the caller function.
        After completing execution of this function, do the JOB(see below)

        0 1 2 3 4   

        This text needs to be printed
        after everything from the caller function
        (text and numbers both) is printed

理论上,我可以将 JOB 放在一个新函数中,并在调用者完成执行后调用该函数。但是我需要我在 my_func 中创建的变量。此外,它会使我的代码更加混乱。

尝试执行:print(i, end=" ") 而不是 yield i

在您的代码中,print(*func()) 中的 *func() 将首先使用生成器 func(),生成一个列表 [0, 1, 2, 3, 4] 并完成 JOB .

也就是说,print(*func())的形式,func中的JOB必须在print函数开始执行其主体代码之前完成。

所以,在我的选择中,你应该按照你说的去做:把 JOB 放在一个新的函数中。