Why doesn't Python remember the initial directory?
andrea crotti
andrea.crotti.0 at gmail.com
Mon Aug 20 10:15:37 EDT 2012
2012/8/20 Roy Smith <roy at panix.com>:
> In article <k0tf8g$adc$1 at news.albasani.net>,
> Walter Hurry <walterhurry at lavabit.com> wrote:
>
>> It is difficult to think of a sensible use for os.chdir, IMHO.
>
> It is true that you can mostly avoid chdir() by building absolute
> pathnames, but it's often more convenient to just cd somewhere and use
> names relative to that. Fabric (a very cool tool for writing remote
> sysadmin scripts), gives you a cd() command which is a context manager,
> making it extra convenient.
>
> Also, core files get created in the current directory. Sometimes
> daemons will cd to some fixed location to make sure that if they dump
> core, it goes in the right place.
>
> On occasion, you run into (poorly designed, IMHO) utilities which insist
> of reading or writing a file in the current directory. If you're
> invoking one of those, you may have no choice but to chdir() to the
> right place before running them.
> --
> http://mail.python.org/mailman/listinfo/python-list
I've done quite a lot of system programming as well, and changing
directory is only a source of possible troubles in general.
If I really have to for some reasons I do this
class TempCd:
"""Change temporarily the current directory
"""
def __init__(self, newcwd):
self.newcwd = newcwd
self.oldcwd = getcwd()
def __enter__(self):
chdir(self.newcwd)
return self
def __exit__(self, type, value, traceback):
chdir(self.oldcwd)
with TempCd('/tmp'):
# now working in /tmp
# now in the original
So it's not that hard to avoid problems..
More information about the Python-list
mailing list