'Storing a variable from a try statement
I have program that is calling into an API every 60 seconds and storing the data. The program is running on a cellular modem that is using Python 2.6. What I'm trying to do is have variables StartTimeConv and EndTimeConv from the try statement stored so that if the try statement fails the except statement can reference them. I've had them declared outside of the try statement, but that it generated a "referenced before assignment" error. What I'm ultimately trying to accomplish with this is if there's a cell signal issue or the API service isn't reachable, the start & stop times can still be referenced and the digital io triggers can still function.
def Client():
threading.Timer(60, Client).start()
# Request Session ID
request = urllib2.Request(url)
b64auth = base64.standard_b64encode("%s:%s" % (username,password))
request.add_header("Authorization", "Basic %s" % b64auth)
result = urllib2.urlopen(request)
# Parse and store Session ID
tree = ET.parse(result)
xml_data = tree.getroot()
sessionid = xml_data[1].text
# Dispatch Event Request
url1 = "SiteURL".format(sessionid)
request1 = urllib2.Request(url1)
result1 = urllib2.urlopen(request1)
# Read and store sys time
sys_time = time.localtime()
# Convert Sys time to datetime object
dt = datetime.fromtimestamp(mktime(sys_time))
# Parse and store Dispatch Event, start and stop time
try:
tree1 = ET.parse(result1)
xml_data1 = tree1.getroot()
dispatchEvent = xml_data1[0][0][2].text
EventStartTime = xml_data1[0][0][14].text
EventEndTime = xml_data1[0][0][1].text
#Convert string time to datetime object
StartTimeConv = datetime.strptime(xml_data1[0][0][14].text, "%a %B %d, %Y %H:%M")
EndTimeConv = datetime.strptime(xml_data1[0][0][1].text, "%a %B %d, %Y %H:%M")
print(dispatchEvent)
print(StartTimeConv)
print(EndTimeConv)
print(dt)
except:
print("No Event")
pass
else:
if dispatchEvent is not None and dt >= StartTimeConv:
set_digital_io('D0', 'on')
elif dispatchEvent is not None and dt <= EndTimeConv:
set_digital_io('D0', 'off')
else:
set_digital_io('D0', 'off')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
