![](/img/trans.png)
[英]How do I distribute data files with a python package such that they're readable?
[英]How do I distribute my pip package with data files correctly?
我有以下軟件包要分發:
mymodule/
data/
1.txt
mymodule/
__init__.py
tests/
test_mymodule.py
setup.py
為了在vitualenv下安裝它,我應用以下命令:
pip install .
一切都安裝正確,但我的數據文件的路徑已損壞。
>>> from mymodule import get
>>> print(get())
...
FileNotFoundError: [Errno 2] No such file or directory: '/home/alexander/Stuff/pip_example/mymodule_test/venv/lib/python3.5/site-packages/mymodule/../data/1.txt'
經過研究,發現文件夾data
是在導致錯誤的virtualenv文件夾的根目錄中創建的。 我應該如何改進代碼以保持測試正常工作並擁有正確的數據文件路徑?
文件內容:
數據/1.txt
yes
mymodule / __ init__.py
import os
src = os.path.join(
os.path.dirname(__file__),
'../data/1.txt'
)
def get():
with open(src) as f:
return f.read().strip()
測試/ test_mymodule.py
import unittest
import mymodule
class MymoduleTest(unittest.TestCase):
def test_get(self):
s = mymodule.get()
self.assertEqual(s, "yes")
setup.py
from distutils.core import setup
data_files = [
('data', ['data/1.txt'])
]
setup(
name='mymodule',
version='0.0',
packages=['mymodule'],
data_files=data_files,
)
我是包裝Python模塊的新手。 請幫我解決這個問題。
================================================== ===================
我發現我需要使用sys.prefix
來訪問virtualenv的根目錄。 換句話說,如果我以這種方式編輯mymodule.__init__.py ,那么一切將正常工作:
import os
import sys
src = os.path.join(sys.prefix, 'data/1.txt')
def get():
with open(src) as f:
return f.read().strip()
但是之后,測試失敗並顯示以下錯誤:
FileNotFoundError: [Errno 2] No such file or directory: '/usr/data/1.txt'
這是因為sys.prefix
是/usr
而沒有激活virtualenv。 我想,所以我需要一種不同的方法來改善包裝。
安裝軟件包時,請檢查文件是否正確分發。
sys.prefix
將找不到“您的”程序包。 模塊的__file__
屬性指向__init__.py
文件。 您可以將其用於基本路徑,如下所示:
import os import mymodule src = os.path.join(os.dirname(mymodule.__file__), 'data/1.txt') def get(): with open(src) as f: return f.read().strip()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.