Python在全局变量赋值后跟异常时的行为

2024-04-24 07:21:02 发布

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

我正在编写一个python函数,它运行一个长时间运行的计算。计算需要仔细调试,所以我的想法是保持状态的全局性,以便能够在IPython中查看它。如果是重要的,状态是张量流模型,计算是它的训练。(更正1:其实并不重要) 当然,如果我看到培训不顺利,我不想等到培训完成后,在IPython中按Ctrl+C,希望复习M.model,进行一些修复等等。你知道吗

不幸的是,如果我要求IPython在KeyboardInterrupt异常之后打印M的值,我将看不到任何值!但怎么可能呢?我很确定培训已经开始了,所以M=Model()行应该已经执行了。你知道吗

更正2:事实证明,在IPython中使用from test import *语法加载文件很重要。


MCVE公司:

# Instructions
# 0. Save this program to test.py file.
# 1. Load the file in IPython with `from test import *` syntax
# 2. call `run()`, wait for some short time.
# 3. Interrupt it with Ctrl+C
# 4. See no global state changed

from typing import Any,Optional
from time import sleep

class Model:
  state:Any

def train(m:Model)->None:
  m.state = 0
  print('Hit Ctrl+C to interrupt "training". Check out (the absence of) M.state')
  while True:
    m.state = m.state + 1
    print('.', end='', flush=True)
    sleep(1)

M:Optional[Model]=None

def run():
  global M
  M=Model()
  train(M)

Tags: thetorunfromtestimportmodeltime