简体   繁体   English

Python ConfigParser无法从命令行运行

[英]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. Python脚本可在IDE中成功运行,但是在尝试通过命令行运行时出现ConfigParser错误。

The error: 错误:

raise NoOptionError(option, section) ConfigParser.NoOptionError: No option 'password' in section: 'database' 引发NoOptionError(选项,部分)ConfigParser.NoOptionError:在“数据库”部分中没有选项“密码”

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. 路径和环境似乎很好,所以问题似乎出在ConfigParser上。 Any thoughts on what might be wrong? 有什么想法可能有问题吗? To re-iterate, the script runs fine from within the IDE (when using Spyder, PyCharm, etc.). 要再次重申,该脚本可以在IDE中正常运行(使用Spyder,PyCharm等时)。 Environment is pointing to Anaconda, as anticipated. 正如预期的那样,环境指向水蟒。

Many thanks for help. 非常感谢您的帮助。

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. 模块名称为“ configparser”(区分大小写。)您提到的IDE可能会执行一些启动初始化,从而掩盖了错误。

Rob (in comments) got me on the right track. 罗伯(在评论中)使我走上了正确的轨道。 The issue is that Python had a different working directory than the script expected. 问题在于Python的工作目录与脚本所预期的不同。 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. 谢谢大家的帮助-非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM