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

  • I think you need to use multiprocess and [kill the process](https://stackoverflow.com/questions/32053618/how-to-to-terminate-process-using-pythons-multiprocessing) when you want to stop it – marsnebulasoup Aug 20 '20 at 14:02

1 Answers1

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

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37