Question

I have a python script that creates a lot of temporary files. If the script terminates early because of a ctrl+c interrupt, I would like to quickly delete those files before the program is allowed to end.

What's the pythonic way handling this?

Was it helpful?

Solution

Open the files in a with statement, if possible, or use a try statement with a finally block that closes the files. If you're using tempfile, the files will automatically be destroyed when closed; otherwise, you may need to delete them yourself in the finally block.

OTHER TIPS

http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    cleanUp()

Either catch and handle KeyboardInterrupt, or set an exit handler with atexit.

Also, tempfile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top