Python inputimeout使用异常:变量text未赋值报错排查
解决inputimeout触发"local variable 'text' referenced before assignment"报错
问题根源很明确:当超时触发异常进入except块时,try里的text = inputimeout(...)根本没执行,text变量从头到尾没被定义,直接return自然会报错。
修复方案一:提前初始化text变量
在try块之前先给text赋一个默认值,比如空字符串或者None,这样不管有没有触发异常,return的时候变量都存在:
def text_receiver(): text = "" # 提前初始化变量 try: text = inputimeout(prompt = "Type the above in one minute: ", timeout = 60) except Exception: print("Time's up! ") return text
修复方案二:在except块内给text赋值
如果超时后需要明确标记输入超时,也可以在except里给text赋值,比如None:
def text_receiver(): try: text = inputimeout(prompt = "Type the above in one minute: ", timeout = 60) except Exception: print("Time's up! ") text = None # 超时后赋值为None return text
更严谨的写法:捕获特定异常
建议不要直接捕获所有Exception,而是明确捕获inputimeout库的TimeoutError,避免意外捕获其他无关异常:
from inputimeout import inputimeout, TimeoutError def text_receiver(): text = "" try: text = inputimeout(prompt = "Type the above in one minute: ", timeout = 60) except TimeoutError: print("Time's up! ") return text
内容的提问来源于stack exchange,提问作者Esandu
相关产品推荐
相关产品推荐

