使用 python configparser 读取 AWS 配置文件时遇到问题

Apr*_*iec 8 python configparser amazon-web-services

我跑去aws configure设置我的访问密钥 ID 和秘密访问密钥。这些现在存储在~/.aws/credentials其中看起来像:

[default]
aws_access_key_id = ######
aws_secret_access_key = #######
Run Code Online (Sandbox Code Playgroud)

我正在尝试访问我正在使用 configparser 编写的脚本的这些键。这是我的代码:

import configparser

def main():
    ACCESS_KEY_ID = ''
    ACCESS_SECRET_KEY = ''

    config = configparser.RawConfigParser()

    print (config.read('~/.aws/credentials')) ## []
    print (config.sections())                 ## []
    ACCESS_KEY_ID = config.get('default', 'aws_access_key_id') ##configparser.NoSectionError: No section: 'default'
    print(ACCESS_KEY_ID)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

我使用python3 script.py. 关于这里发生了什么的任何想法?似乎 configparser 根本没有读取/查找文件。

sna*_*erb 8

configparser.read 不会尝试扩展主目录路径中的前导波浪号“~”。

您可以提供相对或绝对路径

config.read('/home/me/.aws/credentials')
Run Code Online (Sandbox Code Playgroud)

或使用os.path.expanduser

path = os.path.join(os.path.expanduser('~'), '.aws/credentials'))
config.read(path)
Run Code Online (Sandbox Code Playgroud)

或使用pathlib.Path.expanduser

path = pathlib.PosixPath('~/.aws/credentials')
config.read(path.expanduser())
Run Code Online (Sandbox Code Playgroud)