More elegant way to cwd?

Peter Hansen peter at engcorp.com
Mon Dec 27 11:53:57 EST 2004


Kamilche wrote:
> Is there a more elegant way to change the working directory of Python

That depends on how you define "elegant", I guess.

> to the directory of the currently executing script, and add a folder
> called 'Shared' to the Python search path?
> 
> This is what I have. It seems like it could be shorter, somehow.

It could be shorter if you were willing to combine several
function calls on the same line, but I get the impression
you wouldn't consider that more elegant...

> # Switch Python to the current directory
> import os, sys
> pathname, scriptname = os.path.split(sys.argv[0])
> pathname = os.path.abspath(pathname)
> os.chdir(pathname)
> s = os.path.realpath('..')
> s = os.path.join(s, 'Shared')
> sys.path.append(s)
> 
> Thanks for any enhancements you can suggest!

Other than using os.pardir instead of '..', and possibly adding
an "os.path.abspath()" call to the last bit (or does realpath
already do that?  It's unclear from the docs), I can't see
anything fundamental I'd do differently... except package these
functions up as nice clean subroutines, possibly in a library
package, that I could then use in code that would magically
become "elegant" (IMHO) by avoiding the repetition of all
that non-elegant stuff above...

-Peter



More information about the Python-list mailing list