tim_schaaf
tim_schaaf

Reputation: 259

Python ConfigParser won't run from command line

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.

Upvotes: 0

Views: 1831

Answers (2)

tim_schaaf
tim_schaaf

Reputation: 259

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.

Upvotes: 1

elecdrone
elecdrone

Reputation: 13

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.

Upvotes: 0

Related Questions