Finding Script Directory
Fuzzyman
michael at foord.net
Thu Jul 8 03:35:20 EDT 2004
Thomas Heller <theller at python.net> wrote in message news:<7jtf9412.fsf at python.net>...
> 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])
Thanks - that should more than do the trick !
Now just to go back and change all my scripts that probably only work
if run from the right directory.... (assuming files they need will be
in the current directory).. *sigh*
Regards,
Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html
Fuzzy
http://
More information about the Python-list
mailing list