簡體   English   中英

在__init__.py中初始化yaml模塊

[英]initializing yaml module in __init__.py

我正在使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM