Get Path of current Script

A

Alexander Schatten

Hi,

could someone help me with a small problem? I wrote a Python script
that does some RegEx... transformations. Now, this script loads some
configuration data from a file located in the same directory:

open ('config.txt', 'r').

However, this only works when I execute the script being in the
directory where the script is locates, because otherwise, of course,
this config file is not found, as the path is relative. Now my
question: is there an easy way (API) to get the directory of the
currently running script? Something along the line of:

open (API.getCurrentPath + 'config.txt', 'r').


thanks a lot,

cheers

Alex
 
S

Steven D'Aprano

is there an easy way (API) to get the directory of the currently running
script?

import __main__
import os
print os.path.dirname(__main__.__file__)
 
A

Alain Ketterlin

Alexander Schatten said:
could someone help me with a small problem? I wrote a Python script
that does some RegEx... transformations. Now, this script loads some
configuration data from a file located in the same directory:

sys.path[0] is the path to the directory containing the script that the
interpreter started with.

-- Alain.
 
A

Alexander Schatten

Thanks for the comments so far. This sounds to be more complicated in
detail than I expected. I wonder how all the other Python programs and
scripts are doing that...
 
S

Steven D'Aprano

That code is pretty version specific:

In older versions of Python you may have to convert __main__.__file__ to
an absolute path (I'm not sure what 2.6 does as I don't have it to hand,
but 2.5 and earlier could have a relative path).

Ah, so it does -- it looks like __file__ will have an absolute path only
if you call the script with an absolute path, otherwise it will have a
relative path. I've tested that with all versions from 2.2 to 2.7.
Version 2.2 gives an AttributeError when looking up __file__, so I assume
there's no point going back any further.

In any case, would it matter? Whether absolute or relative, the main
thing is that the directory name given should be sufficient for the
script to discover its own location, so as to locate its data files. A
relative path should work for that, so long as the script doesn't change
its own working directory.

In Python 3.x the print will break.

True. But if you're going to be that pedantic, I should have saved the
directory name to a variable, rather than printing it :p

Also, any version can also fail if the code using it is called from an
interactive session as __main__ doesn't always have a __file__
attribute.

Yes, but then it's not a script, is it? :)

So for the paranoid you might use:

print(os.path.dirname(os.path.abspath(
getattr(__main__,'__file__','__main__.py'))))

which falls back to giving you the current directory from a script (and
might be what you want if you haven't changed it since the script
started).

The truly paranoid might prefer to use './__main__.py' instead of a bare
file name, and avoid dealing with the empty string.
 
U

Ulrich Eckhardt

Alexander said:
Thanks for the comments so far. This sounds to be more complicated in
detail than I expected. I wonder how all the other Python programs and
scripts are doing that...

Well, it's not like that's impossible to find out, the source is out
there! :)

Anyhow, you basically have two variants AFAIK:
1. Unix variant
Here, you have the program in the bin directory (e.g. /usr/bin/foo) and the
required data files in a library directory (e.g. /usr/lib/foo/data). The
location of the latter is fixed when the program is installed, i.e. the
path is coded as a placeholder in the source and then replaced according to
the installation-path.

2. Windows variant
Here, the program is installed completely in a folder (e.g. C:\Program
Files\foo) where both the program itself and any other data files are
installed. The special folder (e.g. C:\Program Files) where programs are
stored can be retrieved from the OS, the program-specific path that follows
is usually hard-coded.


Uli
 
G

Grant Edwards

Thanks for the comments so far. This sounds to be more complicated in
detail than I expected. I wonder how all the other Python programs and
scripts are doing that...

The usual answer is "they don't".

At least in the Unix world, finding out the path to the running
program is almost always the wrong way to solve the problem. However,
since we don't know the problem that's being solved, it's hard to
suggest the "right" way to solve it.
 
A

Alexander Schatten

They don't. Hm, ok, I am always for best practices. If there is a
better way to do it I am open for suggestions ;-) How would the best
practice be to load configuration data from a file.

I mean, this is something very common: you write a program or a script
and want to load some configuration data.


thanks


Alex
 
J

John Gordon

In said:
I mean, this is something very common: you write a program or a script
and want to load some configuration data.

There are several good ways to do it:

+ Assume the config file is in the current directory (crude, but it can
work)

+ Put the config file in a known location (i.e. /etc/foorc, ~/.foorc)

+ Put the location of the config file in an environment variable

+ As part of your application's install process, ask the user where the
config file will be stored, and record their answer
 
G

Grant Edwards

They don't. Hm, ok, I am always for best practices. If there is a
better way to do it I am open for suggestions ;-) How would the best
practice be to load configuration data from a file.

I mean, this is something very common: you write a program or a
script and want to load some configuration data.

Indeed that is very common, and there's been a "standard" way to do
that since before dirt.

The standard on Unix is to look in the following places in (this
order), and use the first one you find:

1) The location specified by a command line option (-f or -c is
common).

2) The location specified by an environment variable like
MYPROGNAME_CONFIG.

3) The current directory (usually a "hidden" file name like
.myprognamerc or .myprog.config)

4) The current user's home directory -- same file name as 3).

5) The "configuration directory". Each distro has a spec for where
that is, but it's usually _not_ a hidden file name, and is
somemthing like /etc/myprogname.conf or /etc/myprognamerc. For
locally-installed stuff, it's usually /usr/local/etc/muyprog.conf
or something like that.

Notice that it has nothing to do with the location of the program's
executable.

Not all Unix apps look in all 5 places (#2, is probably not quite as
universal as the rest).

Some apps have a directory of config files instead of a single file,
but the general plan is the same.
 
M

Mario Rol

Hi,

could someone help me with a small problem? I wrote a Python script
that does some RegEx... transformations. Now, this script loads some
configuration data from a file located in the same directory:

open ('config.txt', 'r').

However, this only works when I execute the script being in the
directory where the script is locates, because otherwise, of course,
this config file is not found, as the path is relative. Now my
question: is there an easy way (API) to get the directory of the
currently running script? Something along the line of:

open (API.getCurrentPath + 'config.txt', 'r').

thanks a lot,

cheers

Alex

os.path.join(sys.path[0], 'config.txt')

If the script and config.txt are in /tmp this will return '/tmp/
config.txt' no matter from which directory you started the script.

Mario
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top