2016-03-17 80 views
1

我在Python 3.x中使用yaml(PyYAML 3.11)庫時出現問題。當我打電話import yaml我得到以下錯誤:PyYAML和Python 3.x

Python 3.4.3+ (default, Oct 14 2015, 16:03:50) 
[GCC 5.2.1 20151010] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import yaml 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/mlohr/python-libs/yaml/__init__.py", line 2, in <module> 
    from error import * 
ImportError: No module named 'error' 

error是一個位於YAML目錄中的文件,而是從YAML的__init__.py確實使用絕對導入。我想這就是問題所在,但我不確定。

http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support是一個關於(假設)Python 3支持的短路徑,所以我不確定我是否以錯誤的方式使用它。

當使用yaml的Python腳本使用Python 3時,會發生同樣的問題(這是我發現問題的方式)。

使用Python 2.7和2.6,它沒有問題。

任何想法/建議如何得到這個工作?

+0

您是如何安裝PyYAML的?點子?的setup.py?壓縮包?你用sudo權限安裝它嗎? – larsbutler

+0

你的回溯提示你實際上有一個PyYAML的舊版本,因爲'from error import *'不是絕對導入(就像你說的PyYAML 3.11使用的那樣)。 –

+0

您使用2.x安裝並從PyYAML 3.11獲得了源代碼的2.x版本,如果使用3.x安裝,則會得到不同的源代碼。 – Anthon

回答

3

這似乎是你要麼使用老版本的PyYAML畢竟或者使用Python2安裝PyYAML與Python3作爲一個other answer建議,因爲在你的回溯,我們看到

from error import * 

這是不是絕對的進口。您應該升級,在您的環境中使用Python3源代碼重新安裝PyYAML,或爲Python3軟件包創建新環境。

+0

它不是舊版本,它是已經安裝和重新使用的3.11的2.x源代碼。查看我的答案,查看PyYAML – Anthon

+0

@Anthon中兩個不同頂級'__init __。py'文件的鏈接,我會被詛咒的,甚至沒有跨過我的腦海。隨時downvote這一點,或者我應該編輯或刪除。 –

+0

另外:如何braindead是什麼?就像你所做的那樣,爲什麼不把合併源與compat助手和將來的導入合併。 –

2

您的環境受到污染。如果你創建(臨時)的virtualenv這工作不會有問題:

$ mktmpenv -p /opt/python/3.4/bin/python 
Running virtualenv with interpreter /opt/python/3.4/bin/python 
Using base prefix '/opt/python/3.4' 
New python executable in /home/venv/tmp-504ff2573d39ad0c/bin/python 
Installing setuptools, pip, wheel...done. 
This is a temporary environment. It will be deleted when you run 'deactivate'. 
(tmp-504ff2573d39ad0c) $ pip install pyyaml 
Collecting pyyaml 
Installing collected packages: pyyaml 
Successfully installed pyyaml-3.11 
(tmp-504ff2573d39ad0c) $ python 
Python 3.4.3 (default, Jun 5 2015, 09:05:22) 
[GCC 4.8.2] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import yaml 
>>> 

這個最可能的原因是你重新使用YAML作爲安裝Python的2.X.對於2.x3.x安裝,PyYAML源實際上是不同的。

最簡單的解決方法是安裝和使用ruamel.yaml(免責聲明:我是該包的作者),這是PyYAML的升級,其中源再次重新組合。