Search code examples
python-2.7configparser

ConfigParser does not load sections when run via crontab


When I run python script via command line, everything works just perfect, but wehn the script is being running from cron ConfigParser creates an empty list of sections

me = singleton.SingleInstance()

######### Accessing the configuration file #######################################
config = ConfigParser.RawConfigParser()
config.read('./matrix.cfg')
sections = config.sections()

######### Build the current map ##################################################
print sections

Here is the cron job

* * * * * /usr/bin/python /etc/portmatrix/matrix.py | logger

and here is the output

Feb 12 12:59:01 dns01 CRON[30879]: (root) CMD (/usr/bin/python /etc/portmatrix/matrix.py | logger)
Feb 12 12:59:01 dns01 logger: []

Solution

  • ConfigParser tries to read the file ./matrix.cfg.

    Now the path of this file is ./ which means in the current directory.

    So what assumption do you make about the current directory when being run from cron? (I guess you have a file /etc/portmatrix/matrix.cfg and you assume that ./ really means "in the same directory as the running script" - this however is not true)

    The simple fix is to provide the full path to the configuration file. E.g.:

    config = ConfigParser.RawConfigParser()
    config.read('/etc/portmatrix/matrix.cfg')