Finding Script Directory

Thomas Heller theller at python.net
Wed Jul 7 17:36:13 CEST 2004


Peter Hansen <peter at engcorp.com> writes:

> Fuzzyman wrote:
>
>> What's the best, cross platform, way of finding out the directory a
>> script is run from ?
>> I've googled a bit, but can't get a clear answer.
>
> I've seen twenty threads on this and I still don't know/recall
> whether there's a clear answer. :-(
>
>> On sys.argv[0] the docs say :
>> argv[0] is the script name (it is operating system dependent whether
>> this is a full pathname or not).
>> So this doesn't seem to be the answer.
>
> Actually, it's all you've got to work with.  On Linux and Windows,
> at least, it's got either just the script name, if you're running
> from the current directory, or a path (relative or absolute) to
> the directory where the script is run from.  It's like this whether
> py2exe'd or not, too.
>
> __file__ could be of assistance, but it doesn't exist when
> you've py2exe the thing...
>
>> The script directory is always *somewhere* in sys.path - but not
>> always in position 0. If you use py2exe then sys.path[0] is the
>> zipfile it does the imports from !!
>
> Yeah, sys.path isn't much good for this sort of thing.

The samples\simple\hello.py script can be used for experimentation, and
it prints all the items that may be useful.  Here is the output when
the exe-file's directory is on the PATH:

c:\>hello
Hello from py2exe
frozen 'console_exe'
sys.path ['c:\\sf\\py2exe\\py2exe\\samples\\simple\\dist\\library.zip']
sys.executable c:\sf\py2exe\py2exe\samples\simple\dist\hello.exe
sys.prefix c:\sf\py2exe\py2exe\samples\simple\dist
sys.argv ['hello']

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

Thomas



More information about the Python-list mailing list