Find directory name of file?

Fuzzyman fuzzyman at gmail.com
Mon Jan 30 06:53:22 EST 2006


Peter Hansen wrote:
> jmdeschamps at gmail.com wrote:
> > also the function os.cwd()
> > ;-)
>
> I'm not sure how os.cwd() helps, but generally the solution to this
> starts with pointing out that sys.argv[0] usually contains the path to
> the main script, which is often the answer needed.
>
> Recipes have been posted in the past which cover a wider range of
> situations, including when running as a "py2exe'd" program (i.e.
> "frozen"), as the simple solution doesn't cover all cases.
>
> Checking the archives would probably help.
>

There are a couple of functions from `pathutils
<http://www.voidspace.org.uk/python/pathutils.html>`_ that do this
(originally supplied by Thomas Heller I believe) :

def main_is_frozen():
    """Return ``True`` if we're running from a frozen program."""
    import imp
    return (
        # new py2exe
        hasattr(sys, "frozen") or
        # tools/freeze
        imp.is_frozen("__main__"))

def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    if main_is_frozen():
        return os.path.abspath(os.path.dirname(sys.executable))
    return os.path.abspath(os.path.dirname(sys.argv[0]))

just call ``get_main_dir()`` and it works consistently with py2exe'd
scripts and normal scripts.

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> -Peter




More information about the Python-list mailing list