change a file with a context manager

A

Andrea Crotti

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top