0

I have a program that does some work in a timed while loop like so:

import time
While True:
    do something
    time.sleep(60)

I would like to be able to break out of the loop nicely from the console and save some data on the way out. The solution I have thought of is to create a file when I want the program to quit and check for the file inside the loop like so.

from os.path import exists
While True:
    do something
    if exists('exit.txt'):
        print('exiting')
        clean_up()
    time.sleep(60)

Is there a better way?

John
  • 435
  • 6
  • 15
  • Or use setup a condition that fits your case – shellwhale May 18 '22 at 15:55
  • You can use the `break` keyword to exit a loop when a condition is met. Then, outside the `while` loop, make your call to `clean_up()`. – whege May 18 '22 at 15:55
  • 1
    You're probably looking for interrupt cleanup: https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python – amiasato May 18 '22 at 16:01

2 Answers2

2

Put them into try catch statement. When you want to end the loop, exit the cycle through Ctrl+C, and then complete the work you want to finish:

>>> try:
...     while True: pass
... except KeyboardInterrupt:
...     print('hello')
...
[^C]
hello
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
1

Use the break keyword to exit a loop when a condition is met:

from os.path import exists

while True:
    do_something()

    if exists('exit.txt'):
        print('exiting')
        break

    time.sleep(60)

clean_up()

As Mechanic Pig mentioned in his answer, if you want to be able to manually break out of it from the console, you could implement a KeyboardInterrupt handler:

while True:
    try:
        do_something()

        if exists('exit.txt'):
            print('exiting')
            break
        
        else:
            time.sleep(60)
            continue

    except KeyboardInterrupt:
        print('exiting')
        break

clean_up()
whege
  • 1,391
  • 1
  • 5
  • 13