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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top