关于python:UnboundLocalError:赋值前引用的局部变量’error’

UnboundLocalError: local variable 'error' referenced before assignment

我已经研究过关于这个特定错误的其他问题,但是在这些情况下,在这个过程中有一个路径,在这个路径中变量从未被定义,因此在稍后调用时失败。但是,在我的程序中,我在try方法之前设置了变量,在特定条件下,在try方法中更改了这些变量,然后if语句稍后调用它们,但失败了。当python到达if语句并尝试创建变量文本时,它声明变量错误和错误1未定义(在赋值之前引用)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
err = 0
error = 'No Error Set'
error1 = 'No Error1 Set'
try:
    conn = sqlite3.connect(db_dir)
    for row in conn.execute("select max(date) from eod"):
       mxdate = row
    if mxdate == None:
        pass
    else:
        for row in conn.execute('select date, status from eod where date = ?',(mxdate,)):
            _lst_eod = row
    for row in conn.execute("select * from temp"):
        _crnt_eod = row
    conn.close()
except Exception as error:
    error = str(error)
    err = 1
    logged = 0
    try:
        conn.close()
        time = str(right_datetime())[11:19].replace(':','')
        conn = sqlite3.connect(db_dir)
        conn.execute("insert into error_log (date, user, auth, error, _action) values (?,?,?,?,'Failed to select from eod/temp tables.')",(int(str(_date)+time),cred[0],cred[1],error,))
        conn.commit()
        conn.close()
        logged = 1
    except Exception as error1:
        error1 = str(error1)
if err == 1:
    #An error occured here.
    text = '##Error## An error occured while trying to end the day:
'
+error
    if logged == 0:
        text = text+'

A row was written to the error log.'

    else:
        text = text+'

Write to Error Log failed due to error:
'
+error1
else:
    ....carry on with the rest of the program.

在python 3中,当退出except块时,将删除在except SomeException as e:语句中为其分配异常的变量:

1
2
3
4
5
6
7
8
9
10
11
>>> e ="something"
>>> try:
...     1/0
... except ZeroDivisionError as e:
...     print(e)
...
division by zero
>>> e
Traceback (most recent call last):
  File"<stdin>", line 1, in <module>
NameError: name 'e' is not defined

代码中也发生了同样的事情:当退出时,except Exception as error:except Exception as error1:块正在删除errorerror1