python 不同包之間呼叫(包同級)
阿新 • • 發佈:2018-12-30
工程目錄
.
└── com
├── app
│ ├── crawler02.py
│ └── __init__.py
├── core
│ ├── crawler_core.py
│ └── __init__.py
│
│
│
├── crawler01.py
├── __init__.py
│
└── tool
目的
crawler01 和 crawler02都需要呼叫crawler_core(下簡稱f)中的方法。
crawler01 是f的父級目錄下的檔案其呼叫方法是:
#!/usr/bin/env python
#coding=utf-8
from core import crawler_core
if __name__ == '__main__':
url = "url"
html = crawler_core.getHtml(url)
print(html)
crawler02 是f的同級目錄下的檔案其呼叫方法是:
#!/usr/bin/env python
#coding=utf-8
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)+'/' +'..'))
from core import crawler_core
url = "url"
html = crawler_core.getHtml(url)
print(html)
上面是把把當前python程式所在目錄的父目錄的絕對路徑加入到環境變數PYTHON_PATH中。PYTHON_PATH是python的搜尋路徑,再引入模組時就可以從父目錄中搜索得到了
crawler_core的程式碼:python3.X 後使用urllib.request
#!/usr/bin/env python
#coding=utf-8
#簡單爬蟲實現
import urllib.request
def getHtml(url):
page =urllib.request.urlopen(url)
html = ""
for line in page.readlines():
html = html+str(line)+"\n"
return html