Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #17137
| Date | 2011-12-13 14:21 +0000 |
|---|---|
| From | Andrea Crotti <andrea.crotti.0@gmail.com> |
| Subject | Re: change a file with a context manager |
| References | <4EE72FF4.8010203@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3597.1323786099.27778.python-list@python.org> (permalink) |
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?
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: change a file with a context manager Andrea Crotti <andrea.crotti.0@gmail.com> - 2011-12-13 14:21 +0000
csiph-web