为什么我得到“NameError:free variable”?“在封闭范围内赋值之前引用”?

2024-10-02 08:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

前几天,我在Windows10上使用3D-Slicer(v4.11)和python(v3.6.7)编写了一个简单的python代码

源代码如下:

def RunCLI(self, module, params, onCompletedHandler):
    cliNode = slicer.cli.run(module, None, params)

    mask = cliNode.Cancelled | cliNode.Completed

    completed = False

    def OnStatusModified(caller, event):
        nonlocal completed

        if completed: return # Error

        status = cliNode.GetStatus() # Gives the same error for 'cliNode' if I comment the previuos line

        if status & mask != 0:
            completed = True
            onCompletedHandler()

    cliNode.AddObserver('ModifiedEvent', OnStatusModified)
    OnStatusModified(None, None)

它偶尔会给我一个错误:

'NameError: free variable 'completed' referenced before assignment in enclosing scope'.

我不知道它为什么会发生,为什么有时会通过,有时会失败

我不确定cliNode的内部实现是什么(我认为这不重要),但我猜cliNode在另一个线程中运行一个可执行文件,并通过“ModifiedEvent”发出状态更改的信号

谢谢你的帮助


Tags: thenoneifdefstatusmaskparamsslicer

热门问题