python - 通过文件路径运行python时出现KeyError,直接在目录中时没有问题
问题描述
我正在使用带有 AWS 的 Ubuntu18 EC2 实例。我已经安装了 Anaconda 包。
当我直接在适当的目录中并运行python code.py
它时,它运行良好。但是,当我尝试使用文件路径运行脚本时,它不会运行。
实际代码:
作品
$ python AverageAmountofSessions.py
不工作:
$ python mycompany/AverageSessions/AverageAmountofSessions.py
错误:
Traceback (most recent call last):
File "mycompany/AverageSessions/AverageAmountofSessions.py", line 126, in <module>
lambda_handler('event','content')
File "mycompany/AverageSessions/AverageAmountofSessions.py", line 28, in lambda_handler
db_host = db_config['mysql']['host']
File "/home/ubuntu/anaconda3/lib/python3.7/configparser.py", line 958, in getitem
raise KeyError(key)
KeyError: 'mysql'
补充说明:
- 调用两个 .ini 文件以获取登录 gmail 和数据仓库的凭据
- 库:SQLalchemy、matplotlib、pandas、smtplib、configparser
解决方案
看起来它没有找到应该在您的 ini 文件中的密钥 mysql 。也许在你的 scipt 中找到你的 ini 文件的路径不是好的路径
我的意思是如果你像这样打开你的ini文件:
config = configparser.ConfigParser()
config.read('example.ini')
那么 example.ini 与您的 python scipr 所在的位置不是相对的,而是与 $PWD 相关的,这意味着当您运行它时您在 shell 中的位置!
如果您执行类似操作并且 example.ini 与您的 ini 文件位于同一目录中
import os
config = configparser.ConfigParser()
conffile = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'example.ini')
config.read(conffile)
推荐阅读
- ios - 传递到第二个 UIViewController 时无法保存或查看视频
- haproxy - Haproxy 检查是否只有键存在
- android - 如何将 RTF 转换为 android spannable?
- sql - MS SQL:如何从查找表中为每个外键对选择最近的记录
- javascript - 用 js 添加重复的 html 并评估 thymeleaf 表达式
- javascript - Webpack - AngularJS 应用程序无法在 IE11 上运行
- javascript - For-loop 仅适用于特定值
- session - 根据 ASP .NET MVC 5 中的用户角色显示按钮
- angular - AngularDart 猫头鹰旋转木马
- java - Spring Boot 数据源不去 BeanPostProcessor