Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17137 > unrolled thread

Re: change a file with a context manager

Started byAndrea Crotti <andrea.crotti.0@gmail.com>
First post2011-12-13 14:21 +0000
Last post2011-12-13 14:21 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: change a file with a context manager Andrea Crotti <andrea.crotti.0@gmail.com> - 2011-12-13 14:21 +0000

#17137 — Re: change a file with a context manager

FromAndrea Crotti <andrea.crotti.0@gmail.com>
Date2011-12-13 14:21 +0000
SubjectRe: change a file with a context manager
Message-ID<mailman.3597.1323786099.27778.python-list@python.org>
On 12/13/2011 10:59 AM, Andrea Crotti wrote:
> 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 :)


Alright it was probably a stupid idea to start with.
The problem is that if the easy_install is wrong even the imports in the 
module
will not work, so I can't even start to do something.

Another possible option is to just add to the path everything contained 
in that
correct easy_install.pth file.
Or is there a way to reload the path settings?

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web