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.
Python ctrl+c, excute function if early termination
-
24-06-2022 - |
سؤال
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?
المحلول
نصائح أخرى
http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
cleanUp()
لا تنتمي إلى StackOverflow