Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top