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

问题描述 投票:1回答:1

我运行aws configure来设置我的访问密钥ID和秘密访问密钥。这些现在存储在~/.aws/credentials中,如下所示:

[default]
aws_access_key_id = ######
aws_secret_access_key = #######

我正在尝试使用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()

我使用python3 script.py运行脚本。对这里发生的事情有任何想法吗?似乎configparser根本不读取/查找文件。

python amazon-web-services configparser
1个回答
0
投票

[configparser.read不会尝试在主目录的路径中扩展前导波浪号'〜'。

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

config.read('/home/me/.aws/credentials')

或使用os.path.expanduser

path = os.path.join(os.path.expanduser('~'), '.aws/credentials'))
config.read(path)

或使用pathlib.Path.expanduser

path = pathlib.PosixPath('~/.aws/credentials')
config.read(path.expanduser())
© www.soinside.com 2019 - 2024. All rights reserved.