首页 > 解决方案 > 通过文件路径运行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'

补充说明:

标签: pythonubuntu

解决方案


看起来它没有找到应该在您的 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)

推荐阅读