I am using schedule module to remind me to drink water every ten seconds
import schedule
def remindDrink():
print("Drink Water")
while True:
schedule.every().day.at("16:35").do(remindDrink())
So the problem here is that the task gets executed, but immedieately, not at the given time, and VSCode throws a weird error at me
Traceback (most recent call last):
File "e:\Code\Python Code\randomModule.py", line 12, in <module>
schedule.every().day.at("16:31").do(sendNotification())
File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\schedule\__init__.py", line 625, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
PS E:\Code\Python Code>
This is the error, what am I doing wrong?
Same module different approach, I personally prefer this approach because it keeps my work clean, easy to read and to understand at your first glance and ofcourse easy to refactor.
from schedule import every, repeat, run_pending
import time
#repeat(every().day.at("16:35"))
def remindDrink():
print("Drink Water")
while True:
run_pending()
time.sleep(1)
Your broken code fixed:
Your broken code is fixed below, now the choice is yours, you can either use the above code or this:
import schedule
import time
def remindDrink():
print("Drink Water")
schedule.every().day.at("16:35").do(remindDrink)
while True:
schedule.run_pending()
time.sleep(1)
Remove the () from remindDrink() in the last line inside the do() function
Your code should look like this:
schedule.every().day.at("16:35").do(remindDrink)
Refer back to this question: TypeError: the first argument must be callable in scheduler library
quick thought, shedule....do(), within do() you don't run the function, just put the name of the function inside do.
'''
schedule.every().day.at("16:35").do(remindDrink)
'''
Related
I am solving this question from LeetCode: 1116. Print Zero Even Odd
I am running this solution in VS Code with my own main function to understand the issue in depth.
After reading this question and the suggested solutions. In addition to reading this explanation.
I added this code to the code from the solution:
from threading import Semaphore
import threading
def threaded(fn):
def wrapper(*args, **kwargs):
threading.Thread(target=fn, args=args, kwargs=kwargs).start()
return wrapper
and before those functions from the question I added: #threaded
I added a printNumber function and main function to run it on VS Code.
def printNumber(num):
print(num, end="")
if __name__ == "__main__":
a = ZeroEvenOdd(7)
handle = a.zero(printNumber)
handle = a.even(printNumber)
handle = a.odd(printNumber)
Running this code gives me a correct answer but I do not get a new line printed in the terminal after that, I mean for input 7 in my main function, the output is: 01020304050607hostname and not what I want it to be:
01020304050607
hostname
So, I added print("\n") in the main and I saw that I get a random output like:
0102
0304050607
or
0
1020304050607
still without a new line in the end.
When I try to use the join function handle.join() then I get the error:
Exception has occurred: AttributeError 'NoneType' object has no
attribute 'join'
I tried to do this:
handle1 = a.zero(printNumber)
handle2 = a.even(printNumber)
handle3 = a.odd(printNumber)
handle1.join()
handle2.join()
handle3.join()
Still got the same error.
Where in the code should I do the waiting until the threads will terminate?
Thanks.
When I try to use...handle.join()...I get the error: "...'NoneType' object has no attribute, 'join'
The error message means that the value of handle was None at the point in your program where your code tried to call handle.join(). There is no join() operation available on the None value.
You probably wanted to join() a thread (i.e., the object returned by Threading.thread(...). For a single thread, you could do this:
t = Threading.thread(...)
t.start()
...
t.join()
Your program creates three threads, so you won't be able to just use a single variable t. You could use three separate variables, or you could create a list, or... I'll leave that up to you.
Im currently trying to make a playlist function to run in the background of my code. I am using threading and pygame, and the playlist is an array list. I keep getting this error:
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Users\harry\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in
_bootstrap_inner
self.run()
File "C:\Users\harry\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: 'str' object is not callable
this is the related snippet of code:
from threading import Thread
from time import sleep
def playPlaylist(playlist):
mixer.init()
for music in playlist:
mixer.music.load(music)
mixer.music.play()
while mixer.music.get_busy():
sleep(1)
Thread(target=playPlaylist, args=(playlist)).start()
Github repository: https://github.com/M1st3rMinecraft/python-virtual-assistant
The args parameter is supposed to be an iterable (such as a tuple or list) where each element becomes an argument to the function playPlayList. When you specify args=(playlist), the parentheses surrounding playlist does not denote a tuple of one element. For that you would need to specify args=(playlist,). Therefore, the playlist itself is being interpreted as the iterable and each element of it will be considered a separate argument to playPlayList. There must be only currently one element in playlist for if there were, for example, 3, you would get an error message such as:
TypeError: playPlaylist() takes 1 positional argument but 3 were given
So you need to specify: args=(playlist,). That's problem number one.
Since you are not being passed playlist any more but rather the first and only element of that list as the argument, that is probably leading to the second error. But I would think you would get the exception at:
for music in playlist:
But perhaps the first element of playlist is itself iterable. Try fixing the first problem, though, and see what happens.
Try changing Thread(target=playPlaylist, args=(playlist)).start() to Thread(target=playPlaylist, args=(playlist, )).start() it helped in my case. And also check all of the elements in your code in which you are calling functions if they are not strings. If that didn't work share your file with the mixer class so I can help you further.
In CodeSkulptor (online Python coding page) I wrote a simple code, with a time delay. So simple:
import time
time.sleep(5)
print("random string")
When I press run, I got an error message: Line 2: AttributeError: '<invalid type>' object has no attribute 'sleep'
Any ideas what is wrong? Or how can I fix it?
You're doing javascript. You have to go to py3.codeskulptor.org. Your code works fine there.
The module time in CodeSkulptor implements only the time function:
http://www.codeskulptor.org/docs.html#Time
See the content of the module:
http://www.codeskulptor.org/#user44_uEhmhATcPLOytns.py
The documentation of CodeSkulptor3 mentions only the time function in the time module:
http://py3.codeskulptor.org/docs.html#Time
But the sleep function and other functions are present in the implementation:
http://py3.codeskulptor.org/#user301_4e5WktRmz4A193D.py
Note that in CodeSkulptor3 all printing waits the end of the sleep function. So this function is probably useless if you want wait before to print.
I am making a program that uses a loop to run forever and I have a snippet of code below to show you how I acheive the loop. This is just an example and not the actual program. It is the same idea though.
import time
def start():
print "hello"
time.sleep(0.2)
start()
start()
All of my programmer friends tell me not to do this, and use a while loop instead. Like this:
import time
def start():
while True:
print "Hello"
time.sleep(0.2)
start()
Why should I use the while loop instead when both methods work perfectly fine?
Each time you are recursing, you are pushing a frame context onto your program stack. Soon you would have used up your entire allotted stack space causing stackoverflow, no pun intended ;)
The second approach has no such flaws. Hence by the looks of it 2nd is better than 1st approach (unless more of the program is presented).
If you run the program continuously with the recursion, you will get RuntimeError:
Traceback (most recent call last):
File "t.py", line 8, in <module>
start()
File "t.py", line 7, in start
start()
File "t.py", line 7, in start
start()
...
File "t.py", line 7, in start
start()
RuntimeError: maximum recursion depth exceeded
>>> import sys
>>> sys.getrecursionlimit()
1000
the while loop amd recursion both have their advantages and disadvantages but while loop is just a test and conditional jump. wheras ecursion involves pushing a stack frame, jumping, returning, and popping back from the stack.So they might have preferred while loop :)
Python does not have Tail Call Optimization (TCO) and cannot elide the stack. As such, recursion should not be used for an unbound depth (in languages without TCO) lest you get a stack-overflow error!
While the current code might appear to be fine, consider this simple change which will quickly reveal a problem.
def start():
print "hello"
# let's go faster! -- time.sleep(0.2)
start()
start()
i was messing around with classes and thought i could try and make a class just loop
here is what i did:
class A():
def __init__(self):
print 1
self.loop()
def loop(self):
print 2
self.__init__()
A()
it prints 1 & 2 back and fourth for a while then i get a error that starts looping that looks like this:
Traceback (most recent call last):
File "C:/Python27/classloop.py", line 12, in <module>
A()
then it starts looping these two errors back and fourth:
File "C:/Python27/classloop.py", line 4, in __init__
self.loop()
File "C:/Python27/classloop.py", line 9, in loop
self.__init__()
just wondering why this happens all of the sudden why doesnt it just keep looping?
Every function call creates a stack frame, and every return pops a frame off the stack. This means that if you recurse too deep without returning, Python will run out of room on the stack and throw an exception. You can increase the limit, but most of the time, this will only make your program run a bit longer before crashing, or worse, the Python interpreter will corrupt its memory and go crazy.
In python there is a maximum recursion limit.
The default is 1000.
You can see that by typing:
import sys
print sys.getrecursionlimit()
in the terminal.
If you want to increase it use:
sys.setrecursionlimit(10000) # 10000 is just an example