How do I get the path of the current executed file in python?

Posted by Sorin Sbarnea on Stack Overflow See other posts from Stack Overflow or by Sorin Sbarnea
Published on 2010-04-13T18:37:45Z Indexed on 2010/04/13 21:33 UTC
Read the original article Hit count: 239

Filed under:
|

This may seam a newbie question but it is not. It looks that common approaches are not always working:

Currently I know only two options but none of them looks to work an all cases.

sys.argv[0]

This means using path = os.path.abspath(os.path.dirname(sys.argv[0])) but this does not work if you are running from another python script from another directory, and this can really happen in real life.

__file__

this means that path = os.path.abspath(os.path.dirname(__file__)) but I found that this doesn't work:

  • py2exe that doesn't have a __file__ attribute but there is an workaround.
  • when you run from IDLE with execute() there is no __file__ attribute
  • OS X 10.6 where I get NameError: global name '__file__' is not defined

Related questions with incomplete answers:

© Stack Overflow or respective owner

Related posts about python

Related posts about path