簡體   English   中英

將settings.py配置文件加載到dict中

[英]Loading settings.py config file into a dict

假設我有一個名為settings.py的文件,其內容如下:

{
    "translate_tabs_to_spaces": True,
    "word_wrap": "true",
    "font_face": "Monaco",
    "font_size": 14.0,
    "highlight_line": True,
    "ignored_packages":
    [
        ""
    ],
    "what": '''
            This is python file, not json
            '''
}

如何在主應用程序文件app.py中將其設置為名為settings的dict?

謝謝。

為什么不命名dict說settings而不是從settings.py導入它,例如

settings.py

settings = {} # fill with your data

像這樣使用它

>>> from settings import settings
>>> print settings
{}

替代解決方案是在設置模塊級別添加變量並直接使用它們,為什么需要dict? 例如

settings.py

translate_tabs_to_spaces = True
# more settings

像這樣使用它

>>> import settings
>>> settings.translate_tabs_to_spaces
True

您可以使用ast.literal_eval()來安全地執行此操作。

import ast

data="""\
{
    "translate_tabs_to_spaces": True,
    "word_wrap": "true",
    "font_face": "Monaco",
    "font_size": 14.0,
    "highlight_line": True,
    "ignored_packages":
    [
        ""
    ],
    "what": '''
            This is python file, not json
            '''
}\
"""

print(ast.literal_eval(data))

給我們:

{'what': '\n            This is python file, not json\n            ', 'font_size': 14.0, 'translate_tabs_to_spaces': True, 'font_face': 'Monaco', 'word_wrap': 'true', 'highlight_line': True, 'ignored_packages': ['']}

編輯:

鑒於提問者的新評論暗示他希望能夠在他的配置中使用...ast.literal_eval()適合,因為它無法處理省略號。 目前尚不清楚這是否是他的意思,這仍然是對所提問題的一個很好的答案。

事實證明提問者正在談論三重引用字符串,這是正確處理的。

在設置模塊中為設置輸入一個名稱,然后將設置模塊導入模塊並將其加載到變量中

import settings
your_settings = settings.settings_dict

暫無
暫無

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

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