私はプログラミングに非常に慣れていないと言って始めましょう.これは、スクリプトを超えて何かを書く最初の試みです. 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を引数に指定しなくても同じエラーが発生します。どんな助けでも大歓迎です!