python出现local variable 'f' referenced before assiginment""

在函数中使用try...finally....。在使用过程中try中打开文档,finally关闭文档。

由于在try中打开的文档不存在,因而f参数没有存进入,文档根本没打开,就不可能关闭,所以在finally中报错local variable 'f' referenced before assiginment""。

我之前在网上查找说是加global,也没有管用。

解决方法很简单,在函数中try之前提前给'f'赋值,添加f=None

 1     def GetIfConfigmode(cls, ifname):
 2         configmode = "UNKNOWN"
 3         f = None
 4         try:
 5             commands.getstatusoutput("echo ifname=%s >> /tmp/debug.log"%ifname)
 6             f = open("/etc/sysconfig/network-scripts/ifcfg-%s"%ifname, "r")
 7             ifaceRE=re.compile('BOOTPROTO="(.*)"')
 8             for line in f.readlines():
 9                 match = ifaceRE.match(line)
10                 if match:
11                     configmode = match.group(1).strip().upper()
12                     break
13         except Exception, e:
14             pass
15         finally:
16             if f != None:
17                 f.close()
18         return configmode
原文地址:https://www.cnblogs.com/chenyaling/p/5753243.html