Issue with Alarm Function in making my Clock - python

So I have a major issue with my alarm function in the clock I'm making in Python, a Tkinter error regarding two split functions in my code. I printed out the split components in both cases, and all of them seemed to split properly. I do not know what the issue is.
Here is the code
def alarm():
if toggledtime == "AM/PM":
mainAMPM_time = dt.datetime.now().strftime("%H:%M %p")
alarm_timeAMPMmain = get_alarm_time_entry.get()
alarm_timeAMPM,alarm_period= alarm_timeAMPMmain.split(' ')
alarm_hourAMPM, alarm_minutesAMPM = alarm_timeAMPM.split(':')
main_timeAMPM,main_period = mainAMPM_time.split(' ')
main_hourAMPM, main_minutesAMPM = main_timeAMPM.split(':')
print(alarm_timeAMPMmain)
print()
print(alarm_hourAMPM)
print(alarm_minutesAMPM)
print(alarm_period)
print()
else:
mainMilitary_time= dt.datetime.now().strftime("%H:%M")
alarm_timeMilitarymain = get_alarm_time_entry.get()
alarm_hourMilitary, alarm_minutesMilitary = alarm_timeMilitarymain.split(':')
main_hourMilitary, main_minutesMilitary = mainMilitary_time.split(':')
print(alarm_timeMilitarymain)
print()
print(alarm_hourMilitary)
print(alarm_minutesMilitary)
print()
And here is both errors I get. They are similar Tkinter Errors.
Traceback (most recent call last):
File "/home/arnabd/miniconda3/envs/PythonEnV2/lib/python3.9/tkinter/__init__.py",
line 1892, in __call__
return self.func(*args)
File "/home/arnabd/miniconda3/envs/PythonEnV2/lib/python3.9/tkinter/__init__.py",
line 814, in callit
func(*args)
File "/home/arnabd/Documents/PythonVSCODEProjects/Clock.py", line 55, in alarm
alarm_timeAMPM,alarm_period= alarm_timeAMPMmain.split(' ')
ValueError: not enough values to unpack (expected 2, got 1)
Traceback (most recent call last):
File "/home/arnabd/miniconda3/envs/PythonEnV2/lib/python3.9/tkinter/__init__.py",
line 1892, in __call__
return self.func(*args)
File "/home/arnabd/miniconda3/envs/PythonEnV2/lib/python3.9/tkinter/__init__.py",
line 814, in callit
func(*args)
File "/home/arnabd/Documents/PythonVSCODEProjects/Clock.py", line 62, in alarm
alarm_hourMilitary, alarm_minutesMilitary = alarm_timeMilitarymain.split(':')
ValueError: not enough values to unpack (expected 2, got 1)
Here is the output from those print statements:
10:24 AM
10
24
AM
10
17
10:17
Edit: I tried other delimiters and rechecked the output of my code to ensure I am using the right one. I want to say that the alarm actually starts, but does not produce a noise that I coded in. I'll put in the code for that.
if toggledtime == "AM/PM":
if int(alarm_hourAMPM) == int(main_hour) and int(alarm_minutesAMPM) == int(main_minutesAMPM) and alarm_period == main_period:
for i in range(3):
alarm_status_label.config(text='Time Is Up')
print("\a")
get_alarm_time_entry.config(state='enabled')
set_alarm_button.config(state='enabled')
get_alarm_time_entry.delete(0,END)
alarm_status_label.config(text = '')
else:
alarm_status_label.config(text='Alarm Has Started')
get_alarm_time_entry.config(state='disabled')
set_alarm_button.config(state='disabled')
alarm_status_label.after(1000, alarm)
else:
if int(alarm_hourMilitary) == int(main_hourMilitary) and int(alarm_minutesMilitary) == int(main_minutesMilitary):
for i in range(3):
alarm_status_label.config(text='Time Is Up')
print("\a")
get_alarm_time_entry.config(state='enabled')
set_alarm_button.config(state='enabled')
get_alarm_time_entry.delete(0,END)
alarm_status_label.config(text = '')
else:
alarm_status_label.config(text='Alarm Has Started')
get_alarm_time_entry.config(state='disabled')
set_alarm_button.config(state='disabled')
alarm_status_label.after(1000, alarm)

Related

Getting a strange _tkinter.TclError: unknown option

I have made a small game where you progress through your life much like instlife but made in python with Tkinter. It is not complete and no where near being completed as i always get this same error.
This is my code
import tkinter
window = tkinter.Tk()
window.geometry("275x400")
window.title("Life")
year = 1980
age = 0
def ageButton():
global year
global age
year += 1
age += 1
yearText.configure(text=year)
dynamicText.configure("You are %d" %age)
yearText = tkinter.Label(window, text=year, anchor="n", width="270")
dynamicText = tkinter.Label(window, text="You are %d" %age, anchor="n",
width="270", height="495")
ageButton = tkinter.Button(window, text="Age", width="270",
command=ageButton)
ageButton.pack()
yearText.pack()
dynamicText.pack()
window.mainloop()
this is the error i get
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Ed\Desktop\Lifee2\Life2.py", line 16, in ageButton
dynamicText.configure("You are %d" %age)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1482, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1472, in _configure
return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1460, in _getconfigure1
x = self.tk.splitlist(self.tk.call(*args))
_tkinter.TclError: unknown option "-You are 1"
When you call the configure method, you must tell tkinter what value you are changing. In your case you need to change this:
dynamicText.configure("You are %d" %age)
... to this:
dynamicText.configure(text="You are %d" %age)

Having a difficult time resolving "TypeError: 'list' object is not callable" issue

Error:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 207, in
for paramIndex in range(0, 4): TypeError: 'list' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 249, in
print('stream ending') File "/usr/lib/python3/dist-packages/picamera/camera.py", line 758, in
exit
self.close() File "/usr/lib/python3/dist-packages/picamera/camera.py", line 737, in
close
self.stop_recording(splitter_port=port) File "/usr/lib/python3/dist-packages/picamera/camera.py", line 1198, in
stop_recording
encoder.close() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 431, in
close
self.stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 815, in
stop
super(PiVideoEncoder, self).stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 419, in
stop
self._close_output() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 349, in
_close_output
mo.close_stream(output, opened) File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 371, in
close_stream
stream.flush() ValueError: flush of closed file
Relevant Code:
angle = []
distance = []
speed = []
current = []
timestamp = []
parameterList = []
parameterList.extend((angle, distance, speed, current, timestamp))
for paramIndex in range(0, 4): # LINE 207
# Select Range
range = getRange(index, paramIndex + 5)
cell_list = sheet.range(range[0], range[1], range[2], range[3])
cellIndex = 0
for cell in cell_list:
try:
cell.value = parameterList[paramIndex][cellIndex]
except:
print("PI: " + str(paramIndex))
print("CI: " + str(cellIndex))
print("PL LEN: " + str(len(parameterList)))
print("P LEN: " + str(len(parameterList[paramIndex])))
My Thoughts:
The error makes me think that paramIndex is a list and not an integer but the code executes fine for the first four iterations. This makes me think that there is something wrong with my last list (timestamp). The only thing that I can imagine being wrong with my last list is some sort of index out of bounds issue but...
The except block is never hit
The largest value cellIndex reaches is 30 (expected)
The length of parameterList is 5 (expected)
The length of timestamp is 31 (expected)
I am stumped. If anyone can offer some help that would be greatly appreciated.
paramIndex is fine but you need to avoid calling variables the same name as your functions. In this case, range() is a standard python function but you create a variable called 'range'. Thereafter if you tried to use the range function you'd get an 'object is not callable' error because it's trying to use your range object as the standard range function.
If you insist on wanting to keep the range object name then use xrange() instead of range() where you define your for loop and you shouldn't get any conflicts.

Error when get json from Requests.get()

I used requests.get to get json from my webpage but I have recived some error when I run my code.
This is my code:
def get(t):
while 1:
r = requests.get('http://raspberry.site11.com/controller.php')
while r.status_code != 200:
r = requests.get('http://raspberry.site11.com/controller.php')
d=r.json()
dv1=d["Dv1"]
dv2=d["Dv2"]
dv3=d["Dv3"]
dv4=d["Dv4"]
if dv1=="1":
GPIO.output(6,0)
else:
GPIO.output(6,1)
if dv2=="1":
GPIO.output(13,0)
else:
GPIO.output(13,1)
if dv3=="1":
GPIO.output(19,0)
else:
GPIO.output(19,1)
if dv4=="1":
GPIO.output(26,0)
else:
GPIO.output(26,1)
time.sleep(t)
And this is error I was recived:
Unhandled exception in thread started by <function get at 0xb6506930>
Traceback (most recent call last):
File "thread.py", line 33, in get
d=r.json()
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 793, in json
return json.loads(self.text, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 4 - line 1 column 10 (char 3 - 9)
May everyone help me, thanks all so much.
I think you can do
def get_json(data):
try:
return data.json()
except ValueError:
return False
Then
def get(t):
while 1:
r = requests.get('http://raspberry.site11.com/controller.php')
while not get_json(r):
r = requests.get('http://raspberry.site11.com/controller.php')
d = get_json(r)

traceback shows only one line of a multiline command

I have added a small debugging aid to my server. It logs a stack trace obtained from traceback.format_stack()
It contains few incomplete lines like this:
File "/home/...../base/loop.py", line 361, in run
self.outputs.fd_list, (), sleep)
which is not that much helpfull.
The source lines 360 and 361:
rlist, wlist, unused = select.select(self.inputs.fd_list,
self.outputs.fd_list, (), sleep)
If only one line can be part of the stack trace, I would say the line 360 with the function name (here select.select) is the right one, because the stack is created by calling functions.
Anyway, I would prefer the whole (logical) line to be printed. Or at least some context (e.g. 2 lines before). Is that possible? I mean with just an adequate effort, of course.
Tried to add a line continuation character \, but without success.
EPILOGUE:
Based on Jean-François Fabre's answer and his code I'm going to use this function:
def print_trace():
for fname, lnum, func, line in traceback.extract_stack()[:-1]:
print('File "{}", line {}, in {}'.format(fname, lnum, func))
try:
with open(fname) as f:
rl = f.readlines()
except OSError:
if line is not None:
print(" " + line + " <===")
continue
first = max(0, lnum-3)
# read 2 lines before and 2 lines after
for i, line in enumerate(rl[first:lnum+2]):
line = line.rstrip()
if i + first + 1 == lnum:
print(" " + line + " <===")
elif line:
print(" " + line)
"just with adequate effort" this can be done. But it's hack-like
check this example:
import traceback,re,os,sys
r = re.compile(r'File\s"(.*)",\sline\s(\d+)')
def print_trace():
# discard the 2 deepest entries since they're a call to print_trace()
lines = [str.split(x,"\n")[0] for x in traceback.format_stack()][:-2]
for l in lines:
m = r.search(l)
if m != None:
sys.stdout.write(l+"\n")
file = m.group(1)
line = int(m.group(2))-1
if os.path.exists(file):
with open(file,"r") as f:
rl = f.readlines()
tblines = rl[max(line-2,0):min(line+3,len(rl))]
# read 2 lines before and 2 lines after
for i,tl in enumerate(tblines):
tl = tl.rstrip()
if i==2:
sys.stdout.write(" "+tl+" <====\n")
elif tl:
sys.stdout.write(" "+tl+"\n")
def foo():
print_trace()
foo()
output:
File "C:\Users\dartypc\AppData\Roaming\PyScripter\remserver.py", line 63, in <module>
if __name__ == "__main__":
main() <====
File "C:\Users\dartypc\AppData\Roaming\PyScripter\remserver.py", line 60, in main
t = SimpleServer(ModSlaveService, port = port, auto_register = False)
t.start() <====
if __name__ == "__main__":
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\utils\server.py", line 227, in start
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\utils\server.py", line 139, in accept
File "C:\Users\dartypc\AppData\Roaming\PyScripter\remserver.py", line 14, in _accept_method
class SimpleServer(Server):
def _accept_method(self, sock):
self._serve_client(sock, None) <====
class ModSlaveService(SlaveService):
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\utils\server.py", line 191, in _serve_client
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 391, in serve_all
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 382, in serve
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 350, in _dispatch
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 298, in _dispatch_request
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 528, in _handle_call
File "<string>", line 420, in run_nodebug
File "C:\DATA\jff\data\python\stackoverflow\traceback_test.py", line 31, in <module>
print_trace()
foo() <====
EDIT: VPfB suggested the use of extract_stack which is a little less "hacky", no need to parse a string, just get the quadruplet with traceback info (needs to rebuild the text message, but that's better)
import traceback,os,sys
def print_trace():
# discard the 2 deepest entries since they're a call to print_trace()
for file,line,w1,w2 in traceback.extract_stack()[:-2]:
sys.stdout.write(' File "{}", line {}, in {}\n'.format(file,line,w1))
if os.path.exists(file):
line -= 1
with open(file,"r") as f:
rl = f.readlines()
tblines = rl[max(line-2,0):min(line+3,len(rl))]
# read 2 lines before and 2 lines after
for i,tl in enumerate(tblines):
tl = tl.rstrip()
if i==2:
sys.stdout.write(" "+tl+" <====\n")
elif tl:
sys.stdout.write(" "+tl+"\n")
def foo():
print_trace()
foo()
The traceback.format_exception_only function format only one line, except in case of SyntaxError, so…

Handling exceptions in while loop - Python

Here is my code (almost full version for #cdhowie :)):
def getResult(method, argument=None):
result = None
while True:
print('### loop')
try:
print ('### try hard...')
if argument:
result = method(argument)
else:
result = method()
break
except Exception as e:
print('### GithubException')
if 403 == e.status:
print('Warning: ' + str(e.data))
print('I will try again after 10 minutes...')
else:
raise e
return result
def getUsernames(locations, gh):
usernames = set()
for location in locations:
print location
result = getResult(gh.legacy_search_users, location)
for user in result:
usernames.add(user.login)
print user.login,
return usernames
# "main.py"
gh = Github()
locations = ['Washington', 'Berlin']
# "main.py", line 12 is bellow
usernames = getUsernames(locations, gh)
The problem is, that exception is raised, but I can't handle it. Here is an output:
### loop
### try hard...
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 45, in __grow
newElements = self._fetchNextPage()
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 37, in _fetchNextPage
return self.get_page(page)
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 48, in get_page
None
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Requester.py", line 69, in requestAndCheck
raise GithubException.GithubException(status, output)
github.GithubException.GithubException: 403 {u'message': u'API Rate Limit Exceeded for 11.11.11.11'}
Why it doesn't print ### handling exception?
Take a close look at the stack trace in the exception:
Traceback (most recent call last):
File "main.py", line 12, in <module>
usernames = getUsernames(locations, gh)
File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames
for user in result:
File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__
newElements = self.__grow()
...
The exception is being thrown from code being called by the line for user in result: after getResult finishes executing. This means that the API you're using is using lazy evaluation, so the actual API request doesn't quite happen when you expect it to.
In order to catch and handle this exception, you'll need to wrap the code inside the getUsernames function with a try/except handler.

Categories

Resources