我正在使用PyYAML,并且希望能够在我的.yaml文件中使用字符串连接构造函数。
这篇文章展示了如何在PyYAML中添加这样的构造函数:
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
## register the tag handler
yaml.add_constructor('!join', join)
当我在python终端中输入它时,上面的工作。但是,我想把上面的内容放在my_package
的__init__.py
文件中,这样我就可以这样做:
from my_package import yaml # my_package.__init__.py contains the above code
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")
但是,它崩溃了,消息:
AttributeError Traceback (most recent call last)
<ipython-input-1-1107dafdb1d2> in <module>()
----> 1 import simplelearn.yaml
/home/mkg/projects/simplelearn/simplelearn/__init__.py in <module>()
----> 1 import yaml
2
3 def __join(loader, node):
4 '''
5 Concatenates a sequence of strings.
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc in <module>()
AttributeError: 'module' object has no attribute 'add_constructor'
怎么回事?为什么python找不到yaml.add_constructor
?
从文件中加载模块yaml
:
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc
你要么把你自己的文件命名为yaml.py
,要么你确实有那个文件之前并重新命名它,但忘记删除yaml.pyc
。所以你没有用import yaml
加载PyYAML解释器。
import
:
后面包含一个临时行。import yaml
print(yaml.__file__)
你应该看到类似.../site-packages/yaml/__init__.pyc
的东西。