sys.path and win32 services (was: importerror)

Laszlo Zsolt Nagy gandalf at
Wed Aug 17 16:03:10 CEST 2005

>Why do you think str() is needed here?
Because I'm not sure if sys.path was overwritten or changed. Some bad 
modules could overwrite sys.path with another list. I know I'm paranoid. :-)

>Possibly because sys.path can start with '' which is interpreted as the 
>current directory. Perhaps when the code is started as a windows service 
>[I know nothing about windows services], the current directory is set to 
>%windir%\system32 (where lots of DLLs hang out), and if there is a 
>zlib.dll there, it will get picked up first. Try printing the current 
>directory (see above).
Okay, I did so. I wrote a service that prints out sys.path into a 
logfile. Here is the result:

sys.path=['C:\\Python24\\lib\\site-packages\\win32', 'T:\\Python\\Lib', 
'C:\\WINDOWS\\system32\\', 'C:\\WINDOWS\\system32', 
'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 
'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', 
'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24', 

The empty string is not on sys.path. This is very strange, because it is 
different when I start the python interactively. The problem was caused 
by "C:\WINDOWS\system32", not the empty string. I'm still not sure why 
it is included in sys.path, and why '' is not there? I also checked the 
Python documentation about sys.path, and read the thread mentioned 
before but still sys.path is magical, and magic is not Pythonic. :-)

Anyway, I think I have found the most platform independent solution. 
Here it is:

 >>> import _socket
 >>> import os
 >>> import sys
 >>> dyndir = os.path.split(_socket.__file__)[0]  # This can be 
"/usr/local/lib/python2.4/lib-dynload" or "C:\Python24\DLLs" or whatever
 >>> sys.path.append(dyndir)

In most cases, '_socket.pyd' will be the first module that can be 
imported, and it will by in the dynaload directory for sure.

I feel this is still unclean code. Do you think that it would be nice to 
add new features to the sys module?

sys.dlpath   - could be the path to the lib-dynload or DLLs folder
sys.libpath  - could be the path to the lib folder

>Setting the PYTHONVERBOSE environment variable may assist in showing 
>where modules are being loaded from.
This cannot be used in conjunction with a windows service, because its 
output cannot be seen. :-(

More information about the Python-list mailing list