sys.path and os.chdir

Anton Vredegoor anton at vredegoor.doge.nl
Sat Aug 24 10:26:52 EDT 2002


On 23 Aug 2002 06:22:59 -0700, Ugo_DiGirolamo at InVision.iip.com (ugodiggi)
wrote:

>Am I doing anything wrong?

Sys.path is determined at the time the script is started by the python
interpreter. Import is invoked after the working directory has changed, but
since there is an '' in sys.path[0], import takes this for the current working
directory.

However, the unofficial interpretation of sys.path[0] is that it is the
directory the script is started from.

So sys.path[0] should be 'd:\temp' whether the script is invoked with 

C:\>python D:\temp\test0.py 

or with:

D:\>D:
D:\>cd Temp
D:\Temp>python test0.py

but the second time sys.path[0] is '', which also stands for 'd:\temp' if one
relies on the unofficial interpretation. I would be in favour of making
sys.path[0] always be an absolute path, but maybe this cannot be done on
windows without breaking too much code.

Anton.

p.s.

This is probably what makes the example script work as expected:

## START test0.py
import os, sys

os.chdir('D:\\temp\\temp1')
cwd = os.getcwd()
#add cwd to the path after os.chdir()
sys.path.append(cwd)
print sys.path
print os.getcwd()
import test1
print
print 'Done'

## END   test0.py

## START test1.py
pass
## END   test1.py


test0.py is in D:\temp
test1.py is in D:\temp\temp1

now C:\>python D:\temp\test0.py should be ok.



More information about the Python-list mailing list