[英]I am getting the error that the local variable cruty referenced before assignment
[英]why am I getting local variable referenced before assignment?
我收到一个错误,我花了几个小时试图了解它为什么会发生,但我无法弄清楚。
以下是我的代码,它可以正常工作,直到我断开互联网连接(这就是为什么我在互联网断开连接时异常继续重试),当互联网断开连接时,异常将继续调用 function 并且当互联网恢复时将继续 function 但随后抛出一些错误: [Errno -2] Name or service not known UnboundLocalError: local variable 'ip' referenced before assignment
from time import sleep
from requests_html import HTMLSession
public_ip = ""
def get_ip():
global public_ip
session = HTMLSession()
try:
ip = session.get('https://api.ipify.org').text
except:
print("Exception started... Retrying")
sleep(10)
get_ip()
if ip == public_ip:
print("It's the same")
else:
print("new IP")
print("Old " + public_ip)
print(ip)
public_ip = ip
print("new " + public_ip)
while True:
get_ip()
sleep(10)
当没有互联网时,变量ip
的赋值不起作用,这就是你得到错误的原因,尝试在 try 语句之前初始化变量 ip:
def get_ip():
global public_ip
session = HTMLSession()
ip = ""
try:
ip = session.get('https://api.ipify.org').text
except:
print("Exception started... Retrying")
sleep(10)
get_ip()
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.