Python3 UnboundLocalError:分配前引用的局部变量

时间:2021-01-13 10:50:40

标签: python python-3.x http python-requests

我在python3中编写了以下代码,运行完美:

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
message = ""
run_again = False

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

if "משתמש לא מזוהה" in response.text:
    message = "User Was Logged Out Automatically!"

但是当我切断互联网时,出现以下错误:

    if "משתמש לא מזוהה" in response.text:
UnboundLocalError: local variable 'response' referenced before assignment

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

如果没有互联网,此行将引发异常。

response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)

那会使 response 未定义。 解决此问题的一种方法是将 if 语句移至 try

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
    if "משתמש לא מזוהה" in response.text:
       message = "User Was Logged Out Automatically!"
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

答案 1 :(得分:0)

尝试在 try/except 代码之外初始化响应变量。

答案 2 :(得分:0)

如果 requests.get() 引发异常,则不能使用 response,因为它不会被分配。

您可以改为定义一个函数,例如handle_response 并在 try 块中调用该函数。

def handle_response(response):
   if "משתמש לא מזוהה" in response.text:
        message = "User Was Logged Out Automatically!"

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
message = ""
run_again = False

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
    handle_response(response)
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

只有在 handle_response 没有引发任何异常时才会调用 requests.get() 函数。