2017-01-04 1 views
2

내 맞춤 NYT 모듈을 가져올 수 없습니다. 다음 내가 맥에있어로 내 프로젝트 구조는 다음과 같습니다맞춤 모듈 가져 오기 문제

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() 

다음을 시도했지만 아무 것도 작동하지 않는 것 같습니다.이 문제를 해결하는 방법을 아는 사람이 있습니까? -> 도움 안됨
- Entering Memory 파이썬에서이 코드를 찾을 수 없습니다. 파이썬 2를 사용하고 있기 때문일 수 있습니다. 문제가 해결되면 더 많은 것을 게시 할 수 있습니다. -이 이렇게

+1

상대적인 수입은 (초기 학습 곡선으로도 그렇다하더라도) 매우 간단합니다 :'from ..lib.nyt import NYT' –

+0

슬래시로 판단하면, 당신은 비 윈도우 시스템에 있습니다. 현재 디렉토리가 파이썬 경로에 없을 수도 있습니다. 커맨드 라인에서'python -c 'import articulation''을 실행하고 에러가 있는지보십시오. –

+0

상대 가져 오기를 시도했지만 작동하지 않았습니다. (artvelling/tests/test_nyt.py) 추적 (가장 최근에 마지막으로 호출) : 관절 edohring $의 PWD /사용자/edohring/데스크탑/관절 –

답변

0

아래의 제안에서 상단에 sys.path에 추가 :

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

은 일반적으로 좋은 생각입니다. 때로는 무언가를 테스트 할 때 유용합니다. 단시간에 작업해야하는 일회용 프로그램을 가지고 있다면 버려야 할 수도 있습니다.하지만 일반적으로 들어 가지 못하는 습관이 있습니다. 일단 디렉토리를 옮기거나 다른 사람에게 코드를 제공하면 작업이 중단 될 수 있습니다. 나는 그 일을하는 습관을 갖지 말 것을 조언합니다.

표시되는 오류의 가장 큰 이유는 /Users/edohring/Desktop/articulationsys.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 

출력을 봐라. 파이썬이 모듈을 찾기 위해 들여다 보는 각 디렉토리 경로에 대한 라인을 얻게 될 것이고, 만일 그 경로들 중 어느 것이 상대적이라면 혼란이 발생하지 않도록 해당 절대 경로를 출력 할 것이다. /Users/edohring/Desktop/articulation이이 목록의 어느 곳에도 나타나지 않을 것이라고 생각됩니다.

그 경우,이 쉘 (안 파이썬에서!) 파이썬을 사용하기 전에에서

export PYTHONPATH=".:$PYTHONPATH" 

를 실행하는 것입니다 해결하기 위해 가장 간단한 (그러나 적어도 미래 보장형) 방법이 밝혀지면 귀하의 모듈을 사용하여 무엇이든 할 수 있습니다. PYTHONPATH 환경 변수에 명명 된 디렉토리는 파이썬이 시작될 때 sys.path에 추가됩니다. 이는 터미널 창을 열 때마다 셸이 읽을 수있는 $HOME/.bashrc과 같은 파일에 넣지 않는 한 임시 수정 사항입니다. 이것과 better ways to add the proper directory to sys.path in this question에 관해 읽을 수 있습니다.아마도

스크립트를 실행할 수있는 더 좋은 방법이 디렉토리 /Users/edohring/Desktop/articulation에서 실행해야

python -m articulation.tests.test_nyt 

쉘 명령을 사용하는 것입니다, 또는 적어도 그 디렉토리 명령의 순서를 sys.path에 표시해야 일하다. 그러나 이런 식으로 -m 스위치를 사용하면 파이썬이 sys.path을 약간 다르게 설정하는 방법을 처리합니다. how sys.path is populated in this answer에 대한 자세한 내용을 볼 수 있습니다.