How to Stop python programme (which is continuously giving output ) after sometime

Recommended Answers

All 2 Replies

you may use the Timer class, from the threading module :

import sys, threading

threading.Timer(5.0, lambda : sys.exit(0)).start()

will exit your program after 5 seconds

will exit your program after 5 seconds

This fails, but using os._exit(0) works, instead of sys.exit(0).

In my linux system, the following also works, which is very nice

import thread
import threading

threading.Timer(2.0, lambda : thread.interrupt_main()).start()

    while True:
except KeyboardInterrupt:
    print("We're interrupted: performing cleanup action.")

""" my output:
We're interrupted: performing cleanup action.

The nice thing is that we only plan to raise an exception in the main thread after a certain time instead of exiting directly. This is very pythonic.

commented: you're right, I prefer this way too +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.