0

首先让我说我对编程很陌生,这是我第一次尝试编写超出脚本之外的东西,对我来说如此裸露哈哈。我已多次阅读 configobj 的文档,但我一定遗漏了一些东西。我写了一个类来处理配置文件:

import os, sys, shutil, shlex, configobj
from validate import Validator, ValidateError
from pathlib import Path

class ConfigFile:
    '''Create and edit the preset configuration file.'''
    def __init__(self, configfile):
        config_defaults = {
            "__many__"
            "'ACTIVE' = boolean(default = False)",
            "'PRIMARY' = boolean(default = False)",
            "'ORIENTATION' = string(default = 'normal')",
            "'X' = integer(default = 0)",
            "'Y' = integer(default = 0)",
            "'X_offset' = integer(default = 0)",
            "'Y_offset' = integer(default = 0)"
            }
        if not os.path.exists(configfile):
            Path(configfile).touch()
        self.config_file = configfile
        self.config = configobj.ConfigObj(infile = configfile, indent_type = '    ', configspec = config_defaults)
    def new_preset(self, name):
        self.config[name] = {}
        for i in range(0, len(Display)):
            self.config[name][Display[i].NAME] = {
                'ACTIVE': Display[i].SET_ACTIVE,
                'PRIMARY': Display[i].SET_PRIMARY,
                'ORIENTATION': Display[i].SET_ORIENTATION,
                'X': Display[i].SET_X,
                'Y': Display[i].SET_Y,
                'X_offset': Display[i].SET_X_offset,
                'Y_offset': Display[i].SET_Y_offset
                }
        self.config.write()

尝试创建对象时,出现此错误:

>>> config_ini = os.path.join(CFG_DIR, 'test.ini')
>>> presets = ConfigFile(config_ini)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 18, in __init__
  File "/home/gimmemabrewski/.local/lib/python3.10/site-packages/configobj.py", line 1229, in __init__
    self._load(infile, configspec)
  File "/home/gimmemabrewski/.local/lib/python3.10/site-packages/configobj.py", line 1325, in _load
    self._handle_configspec(configspec)
  File "/home/gimmemabrewski/.local/lib/python3.10/site-packages/configobj.py", line 1939, in _handle_configspec
    configspec = ConfigObj(configspec,
  File "/home/gimmemabrewski/.local/lib/python3.10/site-packages/configobj.py", line 1229, in __init__
    self._load(infile, configspec)
  File "/home/gimmemabrewski/.local/lib/python3.10/site-packages/configobj.py", line 1283, in _load
    raise TypeError('infile must be a filename, file like object, or list of lines.')
TypeError: infile must be a filename, file like object, or list of lines.

我也不确定我的配置规范是否正确,但我还没有走到那一步。根据文档,不需要设置 infile ,但即使我没有infile = configfile作为参数,我也会遇到同样的错误。任何帮助,将不胜感激!

4

0 回答 0