Niek de Klein
Niek de Klein

Reputation: 8824

Getting all hard-coded paths out of the code, how to handle the config file?

I'm trying to get all my hard coded paths out of one of my projects and into a config.ini file. The only thing left is the config file itself. Since I have to read it in:

>>> config = ConfigParser.RawConfigParser()
>>> configReader = config.read('config.ini')

I don't know how to get this out of the code (or if it's even possible). So is there a way to get the hardcoded config path out of the code?

Upvotes: 1

Views: 2942

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You can find the path to a module by using __file__:

#config.py
pass

Importing the module lets you access the name of the file it was imported from:

#main.py
import os
import config

print config.__file__
print os.path.basename(config.__file__)
print os.path.dirname(config.__file__)

Running this in a console gives:

>>> import main
C:/Users/peterwood/Desktop\config.py
config.py
C:/Users/peterwood/Desktop

Upvotes: 3

ronakg
ronakg

Reputation: 4212

I don't know how to get this out of the code (or if it's even possible).

Not possible AFAIK. The program has to know what file to read somehow. There is nothing wrong with having a hard-coded path of the config file in your program.

Upvotes: 0

X-Istence
X-Istence

Reputation: 16667

Take a command line parameter that specifies where your program can find your configuration file.

Take a look at http://docs.python.org/library/optparse.html and it's newer brother http://docs.python.org/dev/library/argparse.html on how to parse command line parameters in Python.

Upvotes: 0

Related Questions