Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop code after time period [duplicate]

Tags:

python

I would like to call foo(n) but stop it if it runs for more than 10 seconds. What's a good way to do this?

I can see that I could in theory modify foo itself to periodically check how long it has been running for but I would prefer not to do that.

like image 479
graffe Avatar asked Feb 17 '13 11:02

graffe


People also ask

How do I stop a Python code after a certain amount of time?

terminate() function will terminate foo function. p. join() is used to continue execution of main thread. If you run the above script, it will run for 10 seconds and terminate after that.

How do you terminate a program in Python?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

How do you stop a Python function from running?

To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.


1 Answers

Here you go:

import multiprocessing import time  # Your foo function def foo(n):     for i in range(10000 * n):         print "Tick"         time.sleep(1)  if __name__ == '__main__':     # Start foo as a process     p = multiprocessing.Process(target=foo, name="Foo", args=(10,))     p.start()      # Wait 10 seconds for foo     time.sleep(10)      # Terminate foo     p.terminate()      # Cleanup     p.join() 

This will wait 10 seconds for foo and then kill it.

Update

Terminate the process only if it is running.

# If thread is active if p.is_alive():     print "foo is running... let's kill it..."      # Terminate foo     p.terminate() 

Update 2 : Recommended

Use join with timeout. If foo finishes before timeout, then main can continue.

# Wait a maximum of 10 seconds for foo # Usage: join([timeout in seconds]) p.join(10)  # If thread is active if p.is_alive():     print "foo is running... let's kill it..."      # Terminate foo     p.terminate()     p.join() 
like image 97
ATOzTOA Avatar answered Sep 19 '22 16:09

ATOzTOA