Terminate script with threads python









up vote
0
down vote

favorite












I have some code:



red = "33[1;31m"
green = "33[1;32m"
yellow = "33[1;33m"
blue = "33[1;34m"
defaultcolor = "33[0m"

class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1

def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()

threadsyy =

threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + 'n')

a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)


And i need to terminate the scipt after 5 seconds. I tried to use sys.exit and killing the process using psutil. Anyone know how to terminate it? I'm trying with:



class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()


and use



watek.kill()


but it doesn't work either.










share|improve this question



















  • 1




    Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
    – Torxed
    Nov 10 at 11:05











  • Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
    – MisterMiyagi
    Nov 10 at 11:15














up vote
0
down vote

favorite












I have some code:



red = "33[1;31m"
green = "33[1;32m"
yellow = "33[1;33m"
blue = "33[1;34m"
defaultcolor = "33[0m"

class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1

def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()

threadsyy =

threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + 'n')

a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)


And i need to terminate the scipt after 5 seconds. I tried to use sys.exit and killing the process using psutil. Anyone know how to terminate it? I'm trying with:



class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()


and use



watek.kill()


but it doesn't work either.










share|improve this question



















  • 1




    Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
    – Torxed
    Nov 10 at 11:05











  • Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
    – MisterMiyagi
    Nov 10 at 11:15












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have some code:



red = "33[1;31m"
green = "33[1;32m"
yellow = "33[1;33m"
blue = "33[1;34m"
defaultcolor = "33[0m"

class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1

def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()

threadsyy =

threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + 'n')

a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)


And i need to terminate the scipt after 5 seconds. I tried to use sys.exit and killing the process using psutil. Anyone know how to terminate it? I'm trying with:



class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()


and use



watek.kill()


but it doesn't work either.










share|improve this question















I have some code:



red = "33[1;31m"
green = "33[1;32m"
yellow = "33[1;33m"
blue = "33[1;34m"
defaultcolor = "33[0m"

class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1

def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()

threadsyy =

threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + 'n')

a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)


And i need to terminate the scipt after 5 seconds. I tried to use sys.exit and killing the process using psutil. Anyone know how to terminate it? I'm trying with:



class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()


and use



watek.kill()


but it doesn't work either.







python python-2.7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 11:06









Torxed

13.1k105386




13.1k105386










asked Nov 10 at 10:53









BleezForMe

133




133







  • 1




    Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
    – Torxed
    Nov 10 at 11:05











  • Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
    – MisterMiyagi
    Nov 10 at 11:15












  • 1




    Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
    – Torxed
    Nov 10 at 11:05











  • Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
    – MisterMiyagi
    Nov 10 at 11:15







1




1




Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
– Torxed
Nov 10 at 11:05





Not sure what the problem is here, your thread dies as soon as x becomes 1 when you do x=1. There's nothing holding the thread alive. Try doing f.isAlive() in your for loop, you'll see that the threads are dead? Also, there's no need to tag this post with both python-3 and python-2, they both live under the same tag as python - meaning they'll get the same attention, it just helps us clarify which type of code we're looking at / the challenges the two different versions come with. And since you're doing print timertime it indicates Python2, so i removed python-3.
– Torxed
Nov 10 at 11:05













Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
– MisterMiyagi
Nov 10 at 11:15




Note that just adding an event to your Thread object will not do anything useful. The code executed in the thread has to actually check and respond to such a termination flag.
– MisterMiyagi
Nov 10 at 11:15












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.



class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)

def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break

while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)

# I'll keep some of the analogy from above here:
threads =
thread = worker()
threads.append(thread)

for f in threads:
f.start()

time.sleep(5)

for f in threads:
print('Is thread alive:', f.isAlive())


The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be), but those threads will look for the main process status and terminate if the main thread dies.



This is one way of creating a thread that will end when the main program does.

The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading



There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?



This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.






share|improve this answer






















  • You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
    – MisterMiyagi
    Nov 10 at 11:18










  • @MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
    – Torxed
    Nov 10 at 11:19










  • FWIW, the solution you posted is one I have not seen yet. ;)
    – MisterMiyagi
    Nov 10 at 11:25










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238220%2fterminate-script-with-threads-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.



class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)

def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break

while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)

# I'll keep some of the analogy from above here:
threads =
thread = worker()
threads.append(thread)

for f in threads:
f.start()

time.sleep(5)

for f in threads:
print('Is thread alive:', f.isAlive())


The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be), but those threads will look for the main process status and terminate if the main thread dies.



This is one way of creating a thread that will end when the main program does.

The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading



There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?



This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.






share|improve this answer






















  • You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
    – MisterMiyagi
    Nov 10 at 11:18










  • @MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
    – Torxed
    Nov 10 at 11:19










  • FWIW, the solution you posted is one I have not seen yet. ;)
    – MisterMiyagi
    Nov 10 at 11:25














up vote
1
down vote



accepted










This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.



class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)

def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break

while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)

# I'll keep some of the analogy from above here:
threads =
thread = worker()
threads.append(thread)

for f in threads:
f.start()

time.sleep(5)

for f in threads:
print('Is thread alive:', f.isAlive())


The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be), but those threads will look for the main process status and terminate if the main thread dies.



This is one way of creating a thread that will end when the main program does.

The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading



There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?



This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.






share|improve this answer






















  • You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
    – MisterMiyagi
    Nov 10 at 11:18










  • @MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
    – Torxed
    Nov 10 at 11:19










  • FWIW, the solution you posted is one I have not seen yet. ;)
    – MisterMiyagi
    Nov 10 at 11:25












up vote
1
down vote



accepted







up vote
1
down vote



accepted






This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.



class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)

def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break

while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)

# I'll keep some of the analogy from above here:
threads =
thread = worker()
threads.append(thread)

for f in threads:
f.start()

time.sleep(5)

for f in threads:
print('Is thread alive:', f.isAlive())


The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be), but those threads will look for the main process status and terminate if the main thread dies.



This is one way of creating a thread that will end when the main program does.

The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading



There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?



This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.






share|improve this answer














This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.



class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)

def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break

while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)

# I'll keep some of the analogy from above here:
threads =
thread = worker()
threads.append(thread)

for f in threads:
f.start()

time.sleep(5)

for f in threads:
print('Is thread alive:', f.isAlive())


The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be), but those threads will look for the main process status and terminate if the main thread dies.



This is one way of creating a thread that will end when the main program does.

The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading



There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?



This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 at 11:20

























answered Nov 10 at 11:15









Torxed

13.1k105386




13.1k105386











  • You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
    – MisterMiyagi
    Nov 10 at 11:18










  • @MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
    – Torxed
    Nov 10 at 11:19










  • FWIW, the solution you posted is one I have not seen yet. ;)
    – MisterMiyagi
    Nov 10 at 11:25
















  • You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
    – MisterMiyagi
    Nov 10 at 11:18










  • @MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
    – Torxed
    Nov 10 at 11:19










  • FWIW, the solution you posted is one I have not seen yet. ;)
    – MisterMiyagi
    Nov 10 at 11:25















You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
– MisterMiyagi
Nov 10 at 11:18




You may just want to flag the question as a duplicate, there are tons of such solutions on SO already.
– MisterMiyagi
Nov 10 at 11:18












@MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
– Torxed
Nov 10 at 11:19




@MisterMiyagi True, and I did. Didn't find the relevant post after posting my answer, and I've already flagged the post as "unclear" because I didn't fully think the question was clear enough to understand the problem - since the threads didn't actually stay alive.. heh. But you're 100% correct.
– Torxed
Nov 10 at 11:19












FWIW, the solution you posted is one I have not seen yet. ;)
– MisterMiyagi
Nov 10 at 11:25




FWIW, the solution you posted is one I have not seen yet. ;)
– MisterMiyagi
Nov 10 at 11:25

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238220%2fterminate-script-with-threads-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

Syphilis

Darth Vader #20