【问题标题】:Custom Module Import Issue自定义模块导入问题
【发布时间】:2017-01-04 16:57:29
【问题描述】:

我似乎无法导入我自己的自定义 NYT 模块。我的项目结构如下,我在mac上:

articulation/
    articulation/
        __init__.py # empty
        lib/
            nyt.py
            __init__.py # empty
        tests/
            test_nyt.py
            __init__.py # empty

当我尝试从第一个父目录运行 python articulation/tests/test_nyt.py 时,我得到了

  File "articulation/tests/test_nyt.py", line 5, in <module>
    from articulation.lib.nyt import NYT
    ImportError: No module named articulation.lib.nyt

我也试过

(venv) Ericas-MacBook-Pro:articulation edohring$ Python -m articulation/tests/test_nyt.py 
/Users/edohring/Desktop/articulation/venv/bin/Python: Import by filename is not supported.

test_nyt.py

import sys
sys.path.insert(0, '../../')
import unittest
#from mock import patch
# TODO: store example as fixture and complete test

from articulation.lib.nyt import NYT

class TestNYT(unittest.TestCase):
    @patch('articulation.lib.nyt.NYT.fetch')
    def test_nyt(self):
        print "hi"
        #assert issubclass(NYT, Article)
        # self.assertTrue(sour_surprise.title == '')"""


nyt.py

        from __future__ import division

import regex as re
import string
import urllib2
from collections import Counter

from bs4 import BeautifulSoup
from cookielib import CookieJar

PARSER_TYPE = 'html.parser'


class NYT:
    def __init__(self, title, url):
        self.url = url
        self.title = title
        self.words = get_words(url)


def get_words(url):
    cj = CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    p = opener.open(url)
    soup = BeautifulSoup(p.read(), PARSER_TYPE)
    # title = soup.html.head.title.string
    letters = soup.find_all('p', class_='story-body-text story-content')
    if len(letters)==0:
        letters = soup.find_all('p', class_='paragraph--story')
    if len(letters)==0:
        letters = soup.find_all('p', class_='story-body-text', )
    words = Counter()
    for element in letters:
        a = element.get_text().split()
        for c in a:
            c = ''.join(ch for ch in c if c.isalpha())
            c = c.lower()
            if len(c) > 0: 
                words[c] += 1
    return words



def test_nyt():
    china_apple_stores = NYT('title_test', 'http://www.nytimes.com/2016/12/29/technology/iphone-china-apple-stores.html?_r=0')
    assert(len(china_apple_stores.words) > 0)
    # print china_apple_stores.words
    fri_brief = NYT('Russia, Syria, 2017: Your Friday Briefing', 'http://www.nytimes.com/2016/12/30/briefing/us-briefing-russia-syria-2017.html')
    assert(fri_brief.title == 'Russia, Syria, 2017: Your Friday Briefing')
    assert(fri_brief.url == 'http://www.nytimes.com/2016/12/30/briefing/us-briefing-russia-syria-2017.html')
    assert(len(fri_brief.words) > 0)
    vet = NYT('title_test', 'http://lens.blogs.nytimes.com/2017/01/03/a-love-story-and-twins-for-a-combat-veteran-amputee/')
    assert(len(vet.words)>0)
    print "All NYT Tests Passed"




#test_nyt()

我尝试了以下方法,但似乎都不起作用 - 有人知道如何解决这个问题吗? - Adding an init.py file to the top directory -> 没用
- Entering Memory Python 找不到这个 - 可能是因为我使用的是 Python 2。如果这是问题,我可以发布更多我尝试过的内容。 - 根据下面的建议在顶部添加 sys.path

【问题讨论】:

  • 相对导入使这变得相当简单(尽管有一个初始学习曲线):from ..lib.nyt import NYT
  • 从正斜杠判断,您使用的是非 Windows 系统。您的当前目录可能不在 Python 路径中。尝试从命令行运行python -c 'import articulation',看看是否有错误。
  • 尝试了相对导入,但没有成功:(venv) edohring-mbp1:articulation edohring$ Python 关节/测试/test_nyt.py 回溯(最近一次调用):文件“关节/测试/ test_nyt.py",第 5 行,在 from ..lib.nyt import NYT ValueError: Attempted relative import in non-package (venv) edohring-mbp1:articulation edohring$ pwd /Users/edohring/Desktop/articulation跨度>
  • 'python -c '导入关节'没有错误

标签: python


【解决方案1】:

这样做:

import sys
sys.path.insert(0, '../../')

通常是个坏主意。有时它在你测试某些东西时很有用,或者你有一个一次性程序,你只需要工作一小段时间然后你就会扔掉,但总的来说这是一个坏习惯,因为一旦您移动目录或将代码提供给其他人,它可能会停止工作。我建议你不要让自己养成这样做的习惯。

出现您所看到的错误的最可能原因是目录/Users/edohring/Desktop/articulation 没有出现在sys.path 中。首先要做的是查看sys.path 中的实际内容,一个很好的方法是暂时将这些行放在test_nyt.py 的顶部:

import os.path, sys
for p in sys.path:
    print(p)
    if not os.path.isabs(p):
        print('  (absolute: {})'.format(os.path.abspath(p)))
sys.exit()

然后运行

python articulation/tests/test_nyt.py

并查看输出。对于 Python 查找其模块的每个目录路径,您将获得一行,如果这些路径中的任何一个是相对的,它还将打印出相应的绝对路径,以免混淆。我猜你会发现/Users/edohring/Desktop/articulation 没有出现在这个列表的任何地方。

如果是这样的话,最直接(但最不经得起未来考验)的修复方法是运行

export PYTHONPATH=".:$PYTHONPATH"

在你使用 Python 本身使用你的模块做任何事情之前,在 shell 中(不是在 Python 中!)。当 Python 启动时,PYTHONPATH 环境变量中命名的目录将被添加到sys.path。这只是一个临时修复,除非你把它放在像$HOME/.bashrc 这样的文件中,每次你打开终端窗口时,shell 都会读取它。你可以阅读这个和better ways to add the proper directory to sys.path in this question。

也许运行脚本的更好方法是使用 shell 命令

python -m articulation.tests.test_nyt

这需要在目录/Users/edohring/Desktop/articulation 中运行,或者至少该目录需要出现在sys.path 中才能使命令起作用。但是以这种方式使用-m 开关会导致Python 处理它设置sys.path 的方式略有不同,它可能对你有用。你可以阅读更多关于how sys.path is populated in this answer的信息。

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 2021-02-20
    • 1970-01-01
    • 2021-03-09
    • 2019-04-04
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多