[Baypiggies] Locating the directory you are executing from
kelly at nttmcl.com
Wed May 7 07:22:36 CEST 2008
Shannon -jj Behrens wrote:
> On Sun, May 4, 2008 at 1:15 PM, Aahz <aahz at pythoncraft.com> wrote:
>> On Sun, May 04, 2008, Jeff Younker wrote:
>> > I have a set of development scripts. The scripts can potentially
>> > be executed from many places. They reference information which is
>> > relative to their installation paths. (These are build scripts.)
>> > The CI system can supply a fixed root, but when run by the developers
>> > I'd like them to be runnable from anywhere in the project, and still
>> > have them work.
>> If you're willing to require that the script directory NOT be on the
>> path, just do some manipulation of sys.argv. Otherwise, __file__ is
>> the right approach.
> Heh, I have this same problem ;)
Here is the snippet I've been using. It supports running both as a
python script and as a binary created by py2exe. It also works on
systems that return paths encoded with with non-ASCII character sets
(e.g. non-U.S. version of Windows).
if hasattr(sys, 'frozen'):
# Running as executable generated by py2exe.
runpath = sys.executable
# Running as python script.
runpath = sys.argv
rundir = os.path.dirname(unicode(runpath,
I am curious though: how is extracting the path from __file__ better
than extracting it from sys.argv? The best I can tell (from simple
test scripts) is that both yield the same results.
More information about the Baypiggies