【问题标题】:initializing yaml module in __init__.py在 __init__.py 中初始化 yaml 模块
【发布时间】:2015-11-08 17:10:13
【问题描述】:

我正在使用 PyYAML,并且希望能够在我的 .yaml 文件中使用字符串连接构造函数。

This post 展示了如何将此类构造函数添加到 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

【问题讨论】:

    标签: python yaml packages pyyaml


    【解决方案1】:

    您从文件中加载模块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 的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-22
      • 2016-06-14
      • 1970-01-01
      • 2018-09-26
      • 2016-04-17
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多