Win32All - Services and current path

Geoffrey Talvola gtalvola at nameconnector.com
Tue Aug 26 18:14:54 CEST 2003


Jeff Hinrichs wrote:
> I'm having trouble nailing down the path to the script directory when
> building a service. I am trying to read in a config file via
> ConfigParser.  When I run the service in debug mode all is well.
> When I start it up normally, via   'myservice.py start' I can't get
> the directory where my service lives.
> 
> When starting the service normally the current path when I try to
> read the file gets set to:
> G:\Python22\lib\site-packages\win32
> probably because that is where pythonservice lives.  So I can't use
> sys.path[0] or parse sys.argv[0]
> to find directory where my config file lives.  I don't want to
> hardcode the path to the config file but
> currently that is the only way I can get the ConfigParser object to
> find my file.
> 
> What am I missing?

I've noticed the same problem.  The __file__ variable helps you out here,
but unfortunately that variable is not defined if the script is run as the
main program (if you're using Python 2.2.X).  Put something like this at the
top of the module:

import os, sys
if __name__ != '__main__':
    mydir = os.path.dirname(os.path.abspath(__file__))
else:
    mydir = os.path.dirname(os.path.abspath(sys.argv[0]))

and I think mydir will be correct regardless of whether the module is
imported, run as a program, or started as a service.

If you're using Python 2.3, it looks like __file__ is always defined, so 

import os, sys
mydir = os.path.dirname(os.path.abspath(__file__))

would probably be sufficient.

- Geoff





More information about the Python-list mailing list