Finding Script Directory

Thomas Heller theller at python.net
Wed Jul 7 12:27:05 EDT 2004


Peter Hansen <peter at engcorp.com> writes:

> 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?

Very similar to what I have.  Here's my version (os.path.abspath should
probably be added).  I hope it also works with Installer, freeze,
cx_Freeze, and earlier versions of py2exe (although I never tested that):

import imp, os, sys

def main_is_frozen():
    return (hasattr(sys, "frozen") or # new py2exe
            hasattr(sys, "importers") # old py2exe
            or imp.is_frozen("__main__")) # tools/freeze

def get_main_dir():
    if main_is_frozen():
        return os.path.dirname(sys.executable)
    return os.path.dirname(sys.argv[0])



More information about the Python-list mailing list