gpt4 book ai didi

Python 3.3 配置文件 - 字典被随机的东西填充

转载 作者:行者123 更新时间:2023-12-01 05:40:10 27 4
gpt4 key购买 nike

过去一个月我一直在制作一个网络服务器,并决定在配置文件中进行全局设置。配置文件内容:

#CONFIG FILE
name = "Webserver"
version = "0.0"
python_version = "Python 33"
database_type = "SQLite 3"

当我想访问文件中的所有值时,我读到我应该使用以下代码:

settingscfg = {}
exec(open("settings.cfg").read(), settingscfg)
print(settingscfg)

但是,我期望输出为 {"name":"Webserver", "version":"0.0", ...etc}。我得到的输出是一个非常奇怪的输出:

{'version': '0.0', 'database_type': 'SQLite 3', 'name': 'Webserver', 'python_version': 'Python 33', '__builtins__': {'slice': <class 'slice'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'iter': <built-in function iter>, 'int': <class 'int'>, 'property': <class 'property'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'PermissionError': <class 'PermissionError'>, 'pow': <built-in function pow>, 'list': <class 'list'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'delattr': <built-in function delattr>, 'NotImplementedError': <class 'NotImplementedError'>, 'AttributeError': <class 'AttributeError'>, 'EOFError': <class 'EOFError'>, 'setattr': <built-in function setattr>, 'super': <class 'super'>, 'globals': <built-in function globals>, 'GeneratorExit': <class 'GeneratorExit'>, 'next': <built-in function next>, 'id': <built-in function id>, 'NameError': <class 'NameError'>, 'WindowsError': <class 'OSError'>, 'chr': <built-in function chr>, 'UnicodeError': <class 'UnicodeError'>, 'ImportWarning': <class 'ImportWarning'>, 'ord': <built-in function ord>, 'BlockingIOError': <class 'BlockingIOError'>, 'TypeError': <class 'TypeError'>, 'divmod': <built-in function divmod>, 'Warning': <class 'Warning'>, 'classmethod': <class 'classmethod'>, 'OSError': <class 'OSError'>, 'getattr': <built-in function getattr>, 'copyright': Copyright (c) 2001-2013 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'str': <class 'str'>, 'sorted': <built-in function sorted>, 'AssertionError': <class 'AssertionError'>, 'SystemExit': <class 'SystemExit'>, 'FileExistsError': <class 'FileExistsError'>, 'BufferError': <class 'BufferError'>, 'tuple': <class 'tuple'>, 'RuntimeError': <class 'RuntimeError'>, 'oct': <built-in function oct>, 'len': <built-in function len>, 'EnvironmentError': <class 'OSError'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'type': <class 'type'>, 'min': <built-in function min>, 'dir': <built-in function dir>, 'ReferenceError': <class 'ReferenceError'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'max': <built-in function max>, 'compile': <built-in function compile>, 'memoryview': <class 'memoryview'>, 'map': <class 'map'>, 'ascii': <built-in function ascii>, '__package__': None, 'reversed': <class 'reversed'>, 'IOError': <class 'OSError'>, 'any': <built-in function any>, 'bytearray': <class 'bytearray'>, 'ChildProcessError': <class 'ChildProcessError'>, 'MemoryError': <class 'MemoryError'>, 'ValueError': <class 'ValueError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'bool': <class 'bool'>, 'KeyError': <class 'KeyError'>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'bin': <built-in function bin>, 'Ellipsis': Ellipsis, 'frozenset': <class 'frozenset'>, 'print': <built-in function print>, 'UserWarning': <class 'UserWarning'>, 'IndentationError': <class 'IndentationError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'SystemError': <class 'SystemError'>, 'NotImplemented': NotImplemented, 'hasattr': <built-in function hasattr>, 'staticmethod': <class 'staticmethod'>, 'False': False, 'exec': <built-in function exec>, 'range': <class 'range'>, 'BytesWarning': <class 'BytesWarning'>, 'sum': <built-in function sum>, 'StopIteration': <class 'StopIteration'>, 'repr': <built-in function repr>, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'abs': <built-in function abs>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'filter': <class 'filter'>, 'format': <built-in function format>, 'locals': <built-in function locals>, 'ConnectionError': <class 'ConnectionError'>, 'ImportError': <class 'ImportError'>, 'complex': <class 'complex'>, 'SyntaxError': <class 'SyntaxError'>, '__name__': 'builtins', 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, '__debug__': True, 'None': None, 'bytes': <class 'bytes'>, 'open': <built-in function open>, 'object': <class 'object'>, 'ArithmeticError': <class 'ArithmeticError'>, 'zip': <class 'zip'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'LookupError': <class 'LookupError'>, 'True': True, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information., 'TimeoutError': <class 'TimeoutError'>, 'FutureWarning': <class 'FutureWarning'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'IndexError': <class 'IndexError'>, 'isinstance': <built-in function isinstance>, 'round': <built-in function round>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'set': <class 'set'>, 'TabError': <class 'TabError'>, 'InterruptedError': <class 'InterruptedError'>, 'help': Type help() for interactive help, or help(object) for help about object., 'IsADirectoryError': <class 'IsADirectoryError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'float': <class 'float'>, 'enumerate': <class 'enumerate'>, 'OverflowError': <class 'OverflowError'>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'Exception': <class 'Exception'>, 'license': Type license() to see the full license text, 'hash': <built-in function hash>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'BaseException': <class 'BaseException'>, 'dict': <class 'dict'>, 'all': <built-in function all>, 'UnicodeWarning': <class 'UnicodeWarning'>, '__build_class__': <built-in function __build_class__>, 'ResourceWarning': <class 'ResourceWarning'>, 'issubclass': <built-in function issubclass>, 'vars': <built-in function vars>, '__import__': <built-in function __import__>, 'hex': <built-in function hex>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'input': <built-in function input>, 'callable': <built-in function callable>, 'eval': <built-in function eval>, 'BrokenPipeError': <class 'BrokenPipeError'>}}

当然,打印的前四个条目是正确的,但之后就有各种奇怪的条目。

编辑:此外,如果我 print(settingscfg.get("version")) 它将返回 0.0,但整个字典仍然充满了垃圾。

最佳答案

在 python 中使用 exec 通常会让人皱眉,因为它只有在你完全信任你的输入数据时才能正常工作,而且它可能会很慢,因为解释器只能在你到达时才开始解析代码。那条线。

对于这样的应用程序,最好使用 configparser ,一个专门为此类事情而制作的标准库模块。为了使用它,您必须稍微更改您的配置文件,以

[CONFIG]
name = "Webserver"
version = "0.0"
python_version = "Python 33"
database_type = "SQLite 3"

为了加载它,您将使用代码

import configparser
config = configparser.ConfigParser()
config.read("settings.cfg")
settingscfg = config["CONFIG"]

然后 settingscfg 将是您要查找的字典。

关于Python 3.3 配置文件 - 字典被随机的东西填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17749576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com