Find the path of a running .py program

Laszlo Nagy gandalf at designaproduct.biz
Mon Mar 12 16:02:35 EDT 2007


  Hi All!

There was a thread here, more than a month ago. It was about finding the 
path of a .py file. I suggested os.abspath(__file__). Others told that 
sys.argv[0] is better. I was not sure why I did not like that solution. 
Now I ran into the problem again, and I now I remember what is the 
problem with that. For windows service applications, it does not work. 
The running program will be pythonservice.exe. Usually we want to know 
where the python program (.py sources) are. So, if you ever write a 
windows service in Python, make sure that you os.chdir to the correct 
directory before you do anything else.

Original thread:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d1a674a2d42741ee/9763b5a8ab48b0a0?lnk=st&q=python+__file__+gandalf+argv&rnum=2&hl=hu#9763b5a8ab48b0a0

Here is a snippet that helped me to overcome the problem:

import sys,os
os.chdir(os.path.split(__file__)[0])


keywords: windows, service, startup directory, startup folder, path of a 
.py program

I hope this comment will help others in the future.

Cheers,

   Laszlo




More information about the Python-list mailing list