1

Everytime I press CTRL-C when I am running a program it displays what line it was executing and then says:

Keyboard Interrupt

However, I am running a program that appends info to text files. It someone presses CTRL-C during that it would only only append what the code got to do before it was interrupted.

I heard of try and except but does that work if I call it at the beggining and someone presses CTRL C during the try phase?

How do I make it so that if anytime in the program someone presses CTRL-C it will not run the program, revert everything it did so far and say:

Exiting Program
Nick M.
  • 259
  • 1
  • 8
  • 22

1 Answers1

2

Give it a try yourself:

This works (if the code is executed too fast on your machine add a zero in the for loop iterator):

a = 0

try:
    for i in range(1000000):
        a = a + 1
except (KeyboardInterrupt, SystemExit):
    print a
    raise

print a

This does not work because data are saved to the file in between. The try block does not undo saving data to the file.

a = 0

try:
    for i in range(1000000):
        if a == 100:
            with open("d:/temp/python.txt", "w") as file:
                file.write(str(a))

        a = a + 1
except (KeyboardInterrupt, SystemExit):
    raise

This works. Data are saved only at the end.

a = 0

try:
    for i in range(1000000):
        a = a + 1
except (KeyboardInterrupt, SystemExit):
    raise

with open("d:/temp/python.txt", "w") as file:
    file.write(str(a))

Therefore prepare the info within the try block and save afterwards.

Another possibility: Save a temporary backup file with the original data and rename the backup file to the original filename in the except block.

Michael Westwort
  • 914
  • 12
  • 24
  • Thanks. I'll try that as soon as I get a chance – Nick M. Jul 25 '16 at 23:14
  • When I write to the file it takes some time. What if it generates and prepares info and then when it starts writing after the except and someone presses ctrl-c? – Nick M. Jul 25 '16 at 23:17
  • Well, at some point you must start writing to the file. If you erase the old file contents before writing the new data, they are lost. If this is not sufficient for you, keep a backup file until the end of the program. Or append the new data to the end of the file and delete the old content from the file at the end. However, deleting the backup file or erasing the old contents can take some time as well; if Ctrl+C is pressed then, you cannot undo either. – Michael Westwort Jul 26 '16 at 06:39