val = 9
def test(flag):
if flag:
val = 1
else:
print("test")
return val if __name__ == '__main__':
ret = test(0)
print(ret)

运行如下:

linux@linux-desktop:~$ python3.3 test.py
fuck
Traceback (most recent call last):
File "test.py", line 10, in <module>
ret = test(0)
File "test.py", line 7, in test
return val
UnboundLocalError: local variable 'val' referenced before assignment

解释如下:

1.意思

本地变量xxx引用前没定义。

2.错误原因:

   
在于python没有变量的声明 , 所以它通过一个简单的规则找出变量的范围 :如果有一个函数内部的变量赋值
,该变量被认为是本地的,所以如果有修改变量的值就会变成局部变量。

3.解决方法:用global关键字来进行说明该变量是全局变量
python代码:
val=9
def test(flag):
    global
val
    if
flag: 
       
val = 1 
   
else: 
       
print(test) 
    return
val

本地变量xxx引用前没定义。

项目中遇到错误如下:

root@UA4300D-spa:~/hanhuakai/pro_07/0703/webview# python3 app.py
ERROR:tornado.application:Uncaught exception GET /top (192.168.2.144)
HTTPRequest(protocol='http', host='192.168.5.41:7777', method='GET', uri='/top', version='HTTP/1.1', remote_ip='192.168.2.144', headers={'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Host': '192.168.5.41:7777', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0', 'Connection': 'keep-alive', 'Referer': 'http://192.168.5.41:7777/', 'Cache-Control': 'max-age=0', 'If-None-Match': '"56b2971f04441fe9644324362487e88a84a776de"'})
Traceback (most recent call last):
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1218, in _when_complete
callback()
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1239, in _execute_method
self._when_complete(method(*self.path_args, **self.path_kwargs),
File "app.py", line 21, in get
self.render("top.htm")
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 615, in render
html = self.render_string(template_name, **kwargs)
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 722, in render_string
return t.generate(**namespace)
File "/usr/lib/python3.2/site-packages/tornado/template.py", line 278, in generate
return execute()
File "top_htm.generated.py", line 5, in _tt_execute
_tt_tmp = _tt_modules.Workstate() # top.htm:34
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1313, in render
rendered = self._active_modules[name].render(*args, **kwargs)
File "app.py", line 2043, in render
info = s.faultyinfo()
File "/usr/lib/python3.2/xmlrpc/client.py", line 1076, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1403, in __request
verbose=self.__verbose
File "/usr/lib/python3.2/xmlrpc/client.py", line 1117, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1132, in single_request
return self.parse_response(resp)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1303, in parse_response
return u.close()
File "/usr/lib/python3.2/xmlrpc/client.py", line 648, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: "<class 'UnboundLocalError'>:local variable 'str_problem_in' referenced before assignment FILENAME: /usr/lib/python3.2/site-packages/ssapi/fm/faultyinfo.py LINE: 912 NAME: print_status_record">
ERROR:tornado.access:500 GET /top (192.168.2.144) 413.94ms

部分代码如下:

 def print_status_record(srp, faulty_item):
global fmadm_msghdl
uurp = srp.uurec
str_time = time.ctime(uurp[0].sec)
faulty_item.time = str_time #"TIME"
faulty_item.event_id = uurp[0].uuid #"EVENT-ID"
faulty_item.msg_id = srp.msgid #"MSG-ID"
faulty_item.severity = srp.severity #"SEVERITY" faulty_item.host = srp.host.server #"Host"
if srp.host.domain :
faulty_item.domain = srp.host.domain #"Domain"
else:
faulty_item.domain = "None" faulty_item.platform = srp.host.platform #"Platform"
str_class_id = srp.host.chassis if srp.host.chassis else "None"
str_product_sn = srp.host.product_sn if srp.host.product_sn else "None" faulty_item.class_id = str_class_id #"Chassis_id"
faulty_item.product_sn = str_product_sn #"Product_sn" if srp.classt : #"Fault class"
str_faulty_class = get_name_list(srp.classt, \
"Fault class :", srp.classt[0].pct, None)
faulty_item.faulty_class = str_faulty_class
else:
faulty_item.faulty_class = "None" if srp.asru : #"Affects"
status = asru_same_status(srp.asru)
if status != -1 :
msg_name_list = get_name_list(srp.asru,"Affects :", 0, None)
msg_asru_status = print_asru_status(status, " ")
str_affects = msg_name_list + msg_asru_status
else:
str_affects = get_name_list(srp.asru,"Affects :", 0, \
print_asru_status)
faulty_item.affects = str_affects
else:
faulty_item.affects = "None" if not srp.fru or not srp.asru : #"Problem in"
if srp.resource :
status = asru_same_status(srp.resource)
if status != -1 :
msg_name_list = get_name_list(srp.resource, \
"Problem in :", 0, None)
msg_rsrc_status = print_rsrc_status(status, " ")
str_problem_in = msg_name_list + msg_rsrc_status
else:
str_problem_in = get_name_list(srp.resource, \
"Problem in :", 0, print_rsrc_status)
faulty_item.problem_in = str_problem_in
else:
faulty_item.problem_in = "None" if srp.fru : #"FRU"
status = asru_same_status(srp.fru)
if status != -1 :
msg_name_list = get_name_list(srp.fru, "FRU :", \
100 if srp.fru[0].pct == 100 else \
srp.fru[0].max_pct, None)
msg_fru_status = print_fru_status(status, " ")
str_fru = msg_name_list + msg_fru_status
else:
str_fru = get_name_list(srp.fru, "FRU :", 100 \
if srp.fru[0].pct == 100 else srp.fru[0].max_pct, \
print_fru_status)
faulty_item.fru = str_fru
else:
faulty_item.fru = "None" if srp.serial and not serial_in_fru(srp.fru, srp.serial) and \
not serial_in_fru(srp.asru, srp.serial) :
str_serial_id = get_name_list(srp.serial, "Serial ID. :", 0, None)
faulty_item.serial_id = str_serial_id
else:
faulty_item.serial_id = "None" #"Serial ID" nvl = srp.uurec[0].event
_fmd_msg_getitem_nv = libfmd_msg.fmd_msg_getitem_nv
_fmd_msg_getitem_nv.restype = c_char_p description = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_DESC)
faulty_item.description = description.decode('UTF-8') #"Description" response = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_RESPONSE)
faulty_item.response = response.decode('UTF-8') #"Response" impact = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_IMPACT)
faulty_item.impact = impact.decode('UTF-8') #"Impact" action = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_ACTION)
faulty_item.action = action.decode('UTF-8') #"Action" return faulty_item

解析:

当if not srp.fru or not srp.asru成立,并且if srp.resource不成立时,这是便直接执行:faulty_item.problem_in = str_problem_in
因此就会出现以上错误信息,值得注意!
错误修改如下:
     if not srp.fru or not srp.asru :            #"Problem in"
if srp.resource :
status = asru_same_status(srp.resource)
if status != -1 :
msg_name_list = get_name_list(srp.resource, \
"Problem in :", 0, None)
msg_rsrc_status = print_rsrc_status(status, " ")
str_problem_in = msg_name_list + msg_rsrc_status
else:
str_problem_in = get_name_list(srp.resource, \
"Problem in :", 0, print_rsrc_status)
12 faulty_item.problem_in = str_problem_in
13 else:
14 faulty_item.problem_in = "None"
else:
faulty_item.problem_in = "None"
 

python 错误--UnboundLocalError: local variable '**' referenced before assignment的更多相关文章

  1. _markupbase.py if not match: UnboundLocalError: local variable 'match' referenced before assignment,分析Python 库 html.parser 中存在的一个解析BUG

    BUG触发时的完整报错内容(本地无关路径用已经用 **** 隐去): **************\lib\site-packages\bs4\builder\_htmlparser.py:78: U ...

  2. 洗礼灵魂,修炼python(23)--自定义函数(4)—闭包进阶问题—>报错UnboundLocalError: local variable 'x' referenced before assignment

    闭包(lexical closure) 什么是闭包前面已经说过了,但是由于遗留问题,所以单独作为一个章节详解讲解下 不多说,看例子: def funx(x): def funy(y): return ...

  3. 变量引用的错误:UnboundLocalError: local variable 'range' referenced before assignment

    class Battery(): """一次模拟电瓶汽车的简单尝试""" def __init__(self,battery_size = ...

  4. UnboundLocalError: local variable 'range' referenced before assignment

    1. 报错信息 UnboundLocalError: local variable 'range' referenced before assignment 2. 代码 class Car(): &q ...

  5. RDO Stack Exception: UnboundLocalError: local variable 'logFile' referenced before assignment

    Issue: When you install RDO stack on CentOS, you may encounter following error. Error: [root@localho ...

  6. 出现UnboundLocalError: local variable 'a' referenced before assignment异常的情况与解决方法

    出现UnboundLocalError: local variable ‘a’ referenced before assignment异常的情况与解决方法字面意思:局部变量赋值前被引用原因:局部变量 ...

  7. This inspection warns about local variables referenced before assignment.

    关于 local variable 'has' referenced before assignment 问题 今天在django开发时,访问页面总是出现错误提示“local variable 'ha ...

  8. jsp的<%@ include file="jsp/common.jsp" %>报错误Duplicate local variable basePath

    将公共引入的文件放到common.jsp中,其他页面引入该jsp即可使用 <%@ page language="java" import="java.util.*& ...

  9. UnboundLocalError: local variable 'foo' referenced before assignment Python常见错误

    在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的, 使用规则:如果在函数中定义了任何东西,如果它只是在函数中使用 ...

随机推荐

  1. windows编程按小时生成日志文件

    这是一个简单的日志记录方法,为了避免单个日志文件过大,所以每个小时生成一个新的日志文件 注意:g_pLogPath 可以带路径,但是必须手动创建好路径,保证目录存在.而且要详细到log文件名,不能带后 ...

  2. C++ 日期时间使用

    #include <time.h> #include <stdio.h> #include <iostream> #include <string> # ...

  3. Layui_2.x_上传插件使用

    一.上传类 package com.ebd.application.common.utils; import java.awt.geom.AffineTransform; import java.aw ...

  4. Codeforces Round #404 (Div. 2)A,B,C

    A. Anton and Polyhedrons 题目链接:http://codeforces.com/contest/785/problem/A 智障水题 实现代码: #include<bit ...

  5. 【Luogu4630】【APIO2018】 Duathlon 铁人两项 (圆方树)

    Description ​ 给你一张\(~n~\)个点\(~m~\)条边的无向图,求有多少个三元组\(~(x, ~y, ~z)~\)满足存在一条从\(~x~\)到\(~z~\)并且经过\(~y~\)的 ...

  6. SharePoint 2013 APP 开发示例 (六)服务端跨域访问 Web Service (REST API)

    上个示例(SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API))是基于JavaScript,运行在web browser内去访问REST AP ...

  7. SharePoint 2013 APP 开发示例 (五)跨域访问 Web Service (REST API)

          虽然 JQuery 也能通过授权header实现跨域, 但SharePoint 提供了更简单的方法,它被实现在SP.RequestExecutor里 .它能访问跨域的服务包括REST AP ...

  8. 一个程序如何在调试时退出调试或退出while循环

    1.退出调试 按Ctrl+C 2.退出while循环 比如 #include <stdio.h> #include <stdlib.h> int main() { long a ...

  9. SURF算法

    一.原理: Sift算法的优点是特征稳定,对旋转.尺度变换.亮度保持不变性,对视角变换.噪声也有一定程度的稳定性:缺点是实时性不高,并且对于边缘光滑目标的特征点提取能力较弱. Surf(Speeded ...

  10. Prometheus MySQL_exporter

    MySQL Exporter mysqld_exporter是用来搜集mysql的性能指标的,适用于mysql5.5及其以上版本 程序安装 下载地址:https://prometheus.io/dow ...