change a file with a context manager
Andrea Crotti
andrea.crotti.0 at gmail.com
Tue Dec 13 05:59:00 EST 2011
So I have the following problem, I need something to copy a file to a
certain position
and restore it after.
So I wrote this simple context manager:
class WithCorrectEasyInstall(object):
def __enter__(self):
import pkg_resources
from shutil import copyfile
easy_install_file =
pkg_resources.resource_filename('psi.devsonly', 'windows_easy_install.pth')
self.global_easy_install =
'c:/python25/Lib/site-packages/easy-install.pth'
# can use mmap, a temporary file or just write to string
self.stored = open(self.global_easy_install).read()
logger.debug("copying the correct easy_install.pth file to the
global position")
copyfile(easy_install_file, self.global_easy_install)
def __exit__(self, type, value, traceback):
#TODO: make sure it's restored also when quitting in some other
ways
# restore the old file
open(self.global_easy_install, 'w').write(self.stored)
logger.debug("restoring the old easy_install.pth file")
The problem is that this is not executed for example when the program is
interrupted
with for example a KeyboardInterrupt.
But that's also an exception, why is it not caught by the context manager?
And if there are better way to do what I'm trying to achieve they are
welcome :)
More information about the Python-list
mailing list