1

I want to know how to stop a running function outside of it. Here is how it should be:

def smth(): time.sleep(5) # Just an example smth.stop() 

Thanks for your help

1
  • I think you need to use multiprocess and kill the process when you want to stop it Commented Aug 20, 2020 at 14:02

1 Answer 1

1

Here's an example using the multiprocessing library:

from multiprocessing import Process import time def foo(): print('Starting...') time.sleep(5) print('Done') p = Process(target=foo) #make process p.start() #start function time.sleep(2) #wait 2 secs p.terminate() #kill it print('Killed') 

Output:

Starting... Killed 

Basically, what this code does is:

  1. Create a process p which runs the function foo when started
  2. Wait 2 seconds to simulate doing other stuff
  3. End the process p with p.terminate()

Since p never passes time.sleep(5) in foo, it doesn't print 'Done'

Run this code online

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.