More elegant way to cwd?

F. Petitjean littlejohn.75 at noos.fr
Mon Dec 27 12:23:05 EST 2004


On Mon, 27 Dec 2004 11:53:57 -0500, Peter Hansen <peter at engcorp.com> wrote:
> 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!
> 
How about ?
import os, sys
pathname, scriptname = os.path.split(sys.argv[0])
pathname = os.path.abspath(pathname)
os.chdir(pathname) # only if you really need to cwd
parent = os.path.dirname(pathname)
parent = os.path.join(parent, 'Shared')
if parent not in sys.path:
    sys.path.append(parent)


Or even :
pathname, scriptname = os.path.split(__file__)
#  pathname  should be an absolute path



More information about the Python-list mailing list