obj = functioning()
from threading import Thread
Thread(target=obj.runCron(cronDetails)).start()
print "new thread started..."
I am runnning this, this should run as new thread for runCron function and should print new thread started. but this is not printing new thread started and not creating new thread
You question is missing some details, e.g. what error message you are getting, etc. – below is a working example mimicked after your code.
#!/usr/bin/env python
import time
class Obj(object):
def runCron(self, cronDetails):
time.sleep(1)
print cronDetails
obj = Obj()
cronDetails = "I'm here."
from threading import Thread
# Note, that the `target` is a function object
# (or a callable in general), we don't actually call it yet!
t = Thread(target=obj.runCron, args=(cronDetails, ))
t.start()
print "New thread started (should be here in a second) ..."
It prints:
New thread started (should be here in a second) ...
I'm here.
Looks like you want to call obj.runCron(cronDetails) inside the thread. But what that code does is to call obj.runCron(cronDetails) first, and then pass the result of that to the Thread class.
If that's the case, the code below should fix it:
obj = functioning()
from threading import Thread
Thread(target=obj.runCron, args=(cronDetails,)).start()
print "new thread started..."
Note that I'm not calling obj.runCron myself anymore, but passing that method with the arguments separately to threading.Thread so it can be called inside the thread with the correct arguments.
If that doesn't do what you want, please provide more info as I asked in the comment.
Related
I'm trying to run a thread in python and am fairly new at it. While going through the basics, when I start a thread, the program doesn't continue with the main program and is stuck in the thread. i.e. it prints only "hello world" and never prints "hi there".
from threading import Thread
import time
def hello_world():
while True:
print("hello world")
time.sleep(5)
t = Thread(target = hello_world())
t.start()
print("hi there")
I'm using spyder IDE.
I searched online for some basic programs in threading but for those, the code works.
How should I proceed?
Your problem is in the line t = Thread(target = hello_world()).
You are trying to create a Thread with the target argument. According to the order of evaluation, Python first needs to know what to assign to target, so it evaluates the RHS. In your case the RHS is hello_world(). So the function is already being called in that exact moment!
So the function executes and enters the infinite loop and the Thread is never even created and your program is stuck.
What you would want to do is pass to target a mere reference to the function, so change said line to:
t = Thread(target = hello_world)
And now the RHS is evaluated as a reference to the given function, and behind the scenes the Thread will be created, making the call to that function, and your main Thread will keep running as expected.
I have a simple thread that looks (simplified) like this:
import threading
import time
def print_coordinates():
return
listener = threading.Thread(name = "listener", target = print_coordinates)
while(1):
listener.start()
time.sleep(1)
listener.start()
time.sleep(1)
Now, I receive the error RuntimeError: threads can only be started once. As far as I understood, return should cause the thread to "silently exit", as mentioned here. What am I doing wrong?
I think you cannot call start more than once.
See here:
http://docs.python.org/2/library/threading.html#threading.Thread.start
It must be called at most once per thread object. It arranges for the
object’s run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the
same thread object.
To call it once more, you will have to create another instance of that thread.
I have a function I'm calling every 5 seconds like such:
def check_buzz(super_buzz_words):
print 'Checking buzz'
t = Timer(5.0, check_buzz, args=(super_buzz_words,))
t.dameon = True
t.start()
buzz_word = get_buzz_word()
if buzz_word is not 'fail':
super_buzz_words.put(buzz_word)
main()
check_buzz()
I'm exiting the script by either catching a KeyboardInterrupt or by catching a System exit and calling this:
sys.exit('\nShutting Down\n')
I'm also restarting the program every so often by calling:
execv(sys.executable, [sys.executable] + sys.argv)
My question is, how do I get that timer thread to shut off? If I keyboard interrupt, the timer keeps going.
I think you just spelled daemon wrong, it should have been:
t.daemon = True
Then sys.exit() should work
Expanding on the answer from notorious.no, and the comment asking:
How can I call t.cancel() if I have no access to t oustide the
function?
Give the Timer thread a distinct name when you first create it:
import threading
def check_buzz(super_buzz_words):
print 'Checking buzz'
t = Timer(5.0, check_buzz, args=(super_buzz_words,))
t.daemon = True
t.name = "check_buzz_daemon"
t.start()
Although the local variable t soon goes out of scope, the Timer thread that t pointed to still exists and still retains the name assigned to it.
Your atexit-registered method can then identify this thread by its name and cancel it:
from atexit import register
def all_done():
for thr in threading._enumerate():
if thr.name == "check_buzz_daemon":
if thr.is_alive():
thr.cancel()
thr.join()
register(all_done)
Calling join() after calling cancel()is based on a StackOverflow answer by Cédric Julien.
HOWEVER, your thread is set to be a Daemon. According to this StackOverflow post, daemon threads do not need to be explicitly terminated.
from atexit import register
def all_done():
if t.is_alive():
# do something that will close your thread gracefully
register(all_done)
Basically when your code is about to exit, it will fire one last function and this is where you will check if your thread is still running. If it is, do something that will either cancel the transaction or otherwise exit gracefully. In general, it's best to let threads finish by themselves, but if it's not doing anything important (please note the emphasis) than you can just do t.cancel(). Design your code so that threads will finish on their own if possible.
Another way would be to use the Queue() module to send and recieve info from a thread using the .put() outside the thread and the .get() inside the thread.
What you can also do is create a txt file and make program write to it when you exit And put an if statement in the thread function to check it after each iteration (this is not a really good solution but it also works)
I would have put a code exemple but i am writing from mobile sorry
well,I wrote a little snappet trying to know how to use python threading .
But strangely the following code just quit quickly without the expected output.
Is it because I shouldn't spawn threads by overiding the run() method?
import threading
from time import sleep
class mythread(threading.Thread):
def __init__(self,target=None,thread_num=5):
threading.Thread.__init__(self,target=None)
self.thn = thread_num
def run(self):
for i in range(self.thn):
t = threading.Thread(target=self.myfunc)
t.start()
t.join()
myfunc(self.thn)
def myfunc(num):
print num,'\tI am doing sth.'
sleep(0.5)
print num,'\tI have done it.'
mythread()
You need to start the thread to make it actually do something:
t = mythread()
t.start()
If you bother to accept a target parameter in your constructor (why?), you shouldn't ignore this parameter. Maybe you want to pass it on to the Thread constructor. (Why?)
When you write mythread(), you instantiate the object. THe default constructor will be called, so __init__() will be executed.
You constructor doesn't have the any instruction of starting the thread.
I've been mucking around with python for a little while and I have recently come up with something involving multithreading... without further ado... heres what I have...
import pythoncom
import wmi
import threading
class Info(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
pythoncom.CoInitialize()
c = wmi.WMI()
detect = c.Win32_ComputerShutdownEvent.watch_for()
detect()
return
if __name__ == '__main__':
Info().start()
for process in c.Win32_Process(Name="something.exe"):
result = process.Terminate()
So my question is... Why does this work? It may be an overall question regarding the process of the inheritence of threading.Thread... but there is no start() def in the class Info() so why does the run def begin?
This is actually a pretty handy application I needed to use to stop an application that always seems to hang when windows shuts down... finding when the windows shutdown event happens was a bit of a headache but luckily tim golden's masterpiece saves the day!
Because it's defined in the parent. Parent classes are checked for attributes if they're not found (or handled) in the child class.
Subclasses of Thread automatically call their run(), when you call start() on them. Start is defined in Thread.
From the docs
There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.
and from docs on start()
It arranges for the object’s run() method to be invoked in a separate thread of control.
Don't you intent to wait the thread has ended before killing process ?
If so:
if __name__ == '__main__':
info = Info()
info.start()
info.join()
for process in c.Win32_Process(Name="something.exe"):
result = process.Terminate()