Python 配置解析器找不到部分?

use*_*405 3 python pygame configparser

我正在尝试使用 ConfigParser 为我的 pygame 游戏读取 .cfg 文件。由于某种原因,我无法让它发挥作用。代码如下所示:

import ConfigParser
def main():
    config = ConfigParser.ConfigParser()
    config.read('options.cfg')
    print config.sections()
    Screen_width = config.getint('graphics','width')
    Screen_height = config.getint('graphics','height')
Run Code Online (Sandbox Code Playgroud)

此文件中的 main 方法在游戏的启动器中调用。我已经测试过了,效果很好。当我运行此代码时,出现此错误:

Traceback (most recent call last):
  File "Scripts\Launcher.py", line 71, in <module>
    Game.main()
  File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main
    Screen_width = config.getint('graphics','width')
  File "c:\python27\lib\ConfigParser.py", line 359, in getint
    return self._get(section, int, option)
  File "c:\python27\lib\ConfigParser.py", line 356, in _get
    return conv(self.get(section, option))
  File "c:\python27\lib\ConfigParser.py", line 607, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'graphics'
Run Code Online (Sandbox Code Playgroud)

问题是,有一个“图形”部分。

我试图读取的文件如下所示:

[graphics]
height = 600
width = 800
Run Code Online (Sandbox Code Playgroud)

我已经验证它实际上被称为 options.cfg。config.sections() 只返回这个:“[]”

在使用相同的代码之前,我已经完成了这项工作,但现在不起作用。任何帮助将不胜感激。

k-n*_*nut 5

可能找不到您的配置文件。在这种情况下,解析器只会产生一个空集。您应该通过检查文件来包装您的代码:

from ConfigParser import SafeConfigParser
import os

def main():
    filename = "options.cfg"
    if os.path.isfile(filename):
        parser = SafeConfigParser()
        parser.read(filename)
        print(parser.sections())
        screen_width = parser.getint('graphics','width')
        screen_height = parser.getint('graphics','height')
    else:
        print("Config file not found")

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