簡體   English   中英

如何從 Python 文件訪問 YAML 數據?

[英]How can I access YAML data from a Python file?

我目前正在使用 discord.py 制作一個 Discord Bot 並具有 YAML 配置。 這是取自我的“hartexConfig.yaml”文件的簡短 YAML 配置:

general:
    hartexToken = 'the bot token'

然后我嘗試在 hartex.py 文件中訪問它:

class Hartex(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__()

    hartexTokenValue = open('HarTex/hartexConfig.yaml', 'r')

    hartexToken = hartexTokenValue['general']['hartexToken']

    yamlStream = True

我該怎么做,還是我完全錯了?

PS 我的意思是訪問特定的數據,就像在這種情況下,我只想從 YAML 文件中讀取 hartexToken。

import yaml

class Hartex(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__()

    with open('HarTex/hartexConfig.yaml', 'r') as hartexConfig:
        # this is the part where your config is actually parsed
        hartexTokenValue = yaml.safe_load(hartexConfig) 

    hartexToken = hartexTokenValue['general']['hartexToken']

你確定 yaml 是正確的嗎? =應該真的是一個: ; 就目前而言,密鑰將是general ,其值hartexToken = 'the bot token'

(你需要安裝pyyaml)

pip install pyyaml


>>> import yaml
>>> with open('demo.yaml','r') as f:
...    datamap = yaml.safe_load(f)
... 
>>> datamap
{'general': "hartexToken = 'the bot token'"}

如果 yaml 確實如您所說,您當然可以split該值以獲得“機器人令牌”。

>>> datamap['general'].split('=')[1]
" 'the bot token'"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM