【问题标题】:Python3 UnboundLocalError: local variable referenced before assignmentPython3 UnboundLocalError:赋值前引用的局部变量
【发布时间】:2021-01-13 10:50:40
【问题描述】:

我在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

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        如果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
        

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

        【讨论】:

          猜你喜欢
          • 2012-11-14
          • 2013-11-29
          • 2019-09-02
          • 1970-01-01
          • 1970-01-01
          • 2015-06-14
          • 2018-06-29
          • 2011-10-31
          • 2020-05-05
          相关资源
          最近更新 更多