Finding Script Directory

Peter Hansen peter at engcorp.com
Wed Jul 7 12:21:32 EDT 2004


Thomas Heller wrote:

> The 'sys.frozen' attribute should be used to determine if the
> script runs from py2exe or from a Python module.

Okay, so here's my first attempt (without checking whether there
is already one in the Cookbook or somewhere) at 'the' canonical
way to find the directory in which the main script or .exe (for frozen
apps) is found.  Note that this uses sys.frozen and therefore
works for frozen apps only if they follow the py2exe mechanism.
(Do any of the others?)

import sys
import os
def getRunDir():
     try:
         sys.frozen
     except AttributeError:
         path = sys.argv[0]
     else:
         path = sys.executable

     return os.path.dirname(os.path.abspath(path))

Comments?  Anyone have a better name?

-Peter



More information about the Python-list mailing list