3

StackOverflow,

Below is the first few lines of my script:

from ConfigParser import SafeConfigParser
from docopt import docopt
import core as scrappy

ARGS = docopt(__doc__, version=scrappy.__version__)
if not ARGS['PATH']:
    ARGS['PATH'] = './'

# load config file
CFG = SafeConfigParser()
if not CFG.read(ARGS['--cfg']):  # call to CFG.read also loads file if it exists
    raise IOError('Configuration file not found.')

The configuration file I'm trying to read is in the same directory as the above script. By default, docopt sets the path to this file to ./file.conf (I have tested this with file.conf with identical results).

The last line of the script is always called, suggesting that the file can't be found. I confirmed this by printing the output of os.getcwd, which revealed that the script's execution directory is whichever directory the terminal was pointing to.

What gives?

What can I do to point to the configuration file?

Louis Thibault
  • 20,240
  • 25
  • 83
  • 152

1 Answers1

5

Use __file__ predefined module attribute. Like this:

module_dir = os.path.dirname(__file__)
CFG = SafeConfigParser()
cfg_full_path = os.path.join(module_dir, ARGS['--cfg'])
if not CFG.read(cfg_full_path): 
    ...
kerim
  • 2,412
  • 18
  • 16