0

Python script runs successfully within IDE, but has ConfigParser error when attempted to run via command line.

The error:

raise NoOptionError(option, section) ConfigParser.NoOptionError: No option 'password' in section: 'database'

The code:

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('settings.ini')

# sets database and API configuration from settings.ini

API_KEY = parser.get('tokens','api_key')

db_user = parser.get('database','user')
db_pwd = parser.get('database','password')
db_host = parser.get('database','host')
db_database =  parser.get('database','database')

Path and Environment appear to be fine, so the issue seems to be with ConfigParser. Any thoughts on what might be wrong? To re-iterate, the script runs fine from within the IDE (when using Spyder, PyCharm, etc.). Environment is pointing to Anaconda, as anticipated.

Many thanks for help.

tim_schaaf
  • 249
  • 2
  • 9
  • What are the `settings.ini` file's contents? Are you sure it's reading the right one (the current working directory may be different when not running the script within the IDE). – martineau Oct 29 '15 at 20:33
  • In your script, print the value of `sys.version` and `os.getcwd()`. Does executing the script in both environments produce identical results for those variables? – Robᵩ Oct 29 '15 at 20:37
  • I think Rob is onto the issue here, os.getcwd() shows '/Users/myname' but the script being executed is in '/Users/myname/scripts'. Any idea what I can do from within the script to make this work? – tim_schaaf Oct 29 '15 at 20:58

2 Answers2

1

Rob (in comments) got me on the right track. The issue is that Python had a different working directory than the script expected. To make the script work, I added:

import sys
import os

os.chdir(os.path.dirname(sys.argv[0]))

... and it works. Thank you everyone for the help - very much appreciated.

tim_schaaf
  • 249
  • 2
  • 9
0

Your import target is incorrect. The module name is "configparser" (case-sensitive.) The IDEs you mentioned probably perform some start-up initialization that masks the error.

elecdrone
  • 13
  • 4
  • ConfigParser was renamed configparser in Python 3. The file will not run, inside or outside of the IDE, as 'configparser'. I'm using Python 2.7.10 (via Anaconda). – tim_schaaf Oct 29 '15 at 20:55