1

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?

2

3 Answers 3

3

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
0

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.

2
  • I want it to work as a python package, not a commandline tool Mar 6, 2012 at 10:09
  • Then have the user of the Python package pass in the location of the configuration file, as required, which they most likely will be getting from the end-user through a parameter passed in upon start of the process.
    – X-Istence
    Mar 6, 2012 at 10:11
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.