我正在尝试使用我的python代码中的pyyaml从textfile中创建一个对象。 我有以下文件:
主要方法:
from make_conf import make_conf
c = make_conf().config
print(c.c)
我要创建代码的对象:
from config import config
import yaml
class make_conf():
def __init__(self):
filename = 'configs.txt'
input_file = open(filename, 'r')
input_string = input_file.read()
self.config = yaml.load(input_string)
我想要创建的对象:
class config():
def __init__(self):
self.c = 4
我想通过pyyaml读取的文本文件:
!!python/object:__main__.config
c: 4
我收到以下错误消息:
/usr/bin/python3.5 "/home/jakob/00 Link to Faubox/spielwiesen/python /main.py"
Traceback (most recent call last):
File "/home/jakob/00 Link to Faubox/spielwiesen/python/main.py", line 4, in <module>
c = make_conf().config
File "/home/jakob/FAUbox/Faubox/spielwiesen/python/make_conf.py", line 11, in __init__
a = yaml.load(input_string)
File "/usr/local/lib/python3.5/dist-packages/yaml/__init__.py", line 72, in load
return loader.get_single_data()
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 37, in get_single_data
return self.construct_document(node)
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 41, in construct_document
data = self.construct_object(node)
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 91, in construct_object
data = next(generator)
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 575, in construct_python_object
instance = self.make_python_instance(suffix, node, newobj=True)
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 552, in make_python_instance
cls = self.find_python_name(suffix, node.start_mark)
File "/usr/local/lib/python3.5/dist-packages/yaml/constructor.py", line 529, in find_python_name
% (object_name, module.__name__), mark)
yaml.constructor.ConstructorError: while constructing a Python object
cannot find 'config' in the module '__main__'
in "<unicode string>", line 1, column 1:
!!python/object:__main__.config
^
如果我在main方法中创建对象,它会以某种方式工作。为什么?我想在main方法之外创建对象!
答案 0 :(得分:0)
找到解决方案:
您必须编写如下文本文件:
!!python/object:config.config
c: 4
第一个配置代表模块名称(文件名,配置类所在的位置),第二个配置是类的名称。 这个修改yaml知道它要创建哪个对象。