473,404 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Finding Script Directory

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.

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.

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

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #1
11 2353
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.

-Peter
Jul 18 '05 #2
Would os.curdir() help? It as least tells you the
current directory. My solution to what I think is
your problem is to put an installdirectory= statement
in my configuration file that gets updated when the
application is installed. That way I always know
where the script is installed. I use Inno Installer
and it is very easy to update configuration files
during installation.

HTH,
Larry Bates
Syscon, Inc.

"Fuzzyman" <mi*****@foord.net> wrote in message
news:80**************************@posting.google.c om...
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.

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.

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

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html

Jul 18 '05 #3
Peter Hansen wrote:
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.

-Peter


Oh, come now, Peter, you've seen this problem solved more times than you
can shake a stick at. The required code is

import os.path, sys
print os.path.abspath(sys.argv[0])

How hard can that be to remember? Didn't realise you were getting so OLD
;-) ...

regards
STeve
Jul 18 '05 #4
Isn't gmail really cool ?? here's one of the text links in the
"Related Pages" column at the right of the page displaying this
thread:

7.2. Finding the path
a free Python book for experienced programmers
www.faqs.org

The link points to: http://www.faqs.org/docs/diveintopyt...sion_path.html

I'm glad google's reading my mail :)

HTH
Steve
- Hide quoted text -

On Wed, 07 Jul 2004 09:58:20 -0400, Peter Hansen <pe***@engcorp.com> wrote:
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.

Jul 18 '05 #5
Steve Holden wrote:
Peter Hansen wrote:
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. :-(

Oh, come now, Peter, you've seen this problem solved more times than you
can shake a stick at. The required code is

import os.path, sys
print os.path.abspath(sys.argv[0])

How hard can that be to remember? Didn't realise you were getting so OLD
;-) ...


Well, I just put that in a nice little .exe created by py2exe,
and running from a directory in my PATH.

Amazing, but when I run it with the current directory set to C:\
it prints only "C:\testpath", and yet the script (well, the EXE)
is actually in a directory called c:\dev\prj189~1\dist ...

Fuzzyman's right: there isn't a clear, conclusive answer, I believe.

(But the above recipe, which I'm sure he found via google,
should work in almost all cases, py2exe and perhaps certain OSes
excluded.)

-but-that-doesn't-mean-i'm-not-getting-old-ly y'rs,
Peter
Jul 18 '05 #6
Peter Hansen <pe***@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\\li brary.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
Jul 18 '05 #7
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?

-Peter
Jul 18 '05 #8
Peter Hansen <pe***@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])
Jul 18 '05 #9
Peter Hansen wrote:
[...]
Well, I just put that in a nice little .exe created by py2exe,
and running from a directory in my PATH.

Amazing, but when I run it with the current directory set to C:\
it prints only "C:\testpath", and yet the script (well, the EXE)
is actually in a directory called c:\dev\prj189~1\dist ...

Fuzzyman's right: there isn't a clear, conclusive answer, I believe.

(But the above recipe, which I'm sure he found via google,
should work in almost all cases, py2exe and perhaps certain OSes
excluded.)

-but-that-doesn't-mean-i'm-not-getting-old-ly y'rs,
Peter


Happily it's still true that the fastest way to get the right answer on
a newsgroup is to suggest the wrong one!

regards
Steve
Jul 18 '05 #10
"Larry Bates" <lb****@swamisoft.com> wrote in message news:<MK********************@comcast.com>...
Would os.curdir() help? It as least tells you the
current directory. My solution to what I think is
your problem is to put an installdirectory= statement
in my configuration file that gets updated when the
application is installed. That way I always know
where the script is installed. I use Inno Installer
and it is very easy to update configuration files
during installation.

HTH,
Larry Bates
Syscon, Inc.
This might be the answer to my problem, part of the problem I'm trying
to solve is an install of a py2exe'd program that is installed with
innosetup.

I'll have to look into this.
Otherwise the magic with os.path.abspath(sys.argv[0]) should do the
trick...

Regards,

Fuzzy
"Fuzzyman" <mi*****@foord.net> wrote in message
news:80**************************@posting.google.c om...
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.

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.

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

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html

Jul 18 '05 #11
Thomas Heller <th*****@python.net> wrote in message news:<7j**********@python.net>...
Peter Hansen <pe***@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/atlantib...thonutils.html
Fuzzy

http://
Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Kevin Thorpe | last post by:
I don't suppose anyone knows of a script/program to try and identify where variables are used assuming register_globals is on? I'm trying to fix an application and would rather not turn it on as...
1
by: Todd Johnson | last post by:
Hey, I have been working on a program that stores information for each user in a subdirectory of the directory in which the script is run. So if my script is in /home/someuser/myprogram, the...
0
by: Gabriel Cooper | last post by:
In one of my python programs has a data file I need to load. My solution was to say: if os.path.exists(os.path.join(os.getcwd(), "config.xml")): self.cfgfile = os.path.join(os.getcwd(),...
3
by: runes | last post by:
Is it a more pythonic way of finding the name of the running script than these? from os import sep from sys import argv print argv.split(sep) # or print locals().split(sep) # or
12
by: jeff elkins | last post by:
I'm creating an app that relies on a configuration file at launch. The file will always exist in the app's installation directory, but I have no control over where that might be. Is there an...
2
by: Robb Meade | last post by:
Hi all, I've written a small form handler script which should work for 'all' (term used loosely) forms... It will email the company, send courtesy emails to the form filler and save data to a...
22
by: Tony Houghton | last post by:
I'm using pygame to write a game called Bombz which needs to save some data in a directory associated with it. In Unix/Linux I'd probably use "~/.bombz", in Windows something like "C:\Documents...
4
by: Larry | last post by:
I have a Perl script using DBD::DB2, that runs during system startup on a Solaris system. The script is working fine during startup on many machines, except on one machine it fails complaining...
12
by: Jeff | last post by:
As I'm learning PHP, I'm making a fair number of mistakes in syntax. In perl, you can turn on reading these errors from the browser by adding this: use CGI::Carp 'fatalsToBrowser'; Is there...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.