如何正确分配带有数据文件的pip包? [英] How do I distribute my pip package with data files correctly?
问题描述
我有以下软件包要分发:
I have a following package to distribute:
mymodule/
data/
1.txt
mymodule/
__init__.py
tests/
test_mymodule.py
setup.py
为了在vitualenv下安装它,我应用以下命令:
In order to install it under a vitualenv I apply this command:
pip install .
一切都安装正确,但我的数据文件的路径已损坏.
Everything is installed fine but the path to my data file becomes broken.
>>> 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文件夹的根目录中创建的.我应该如何改进代码以保持测试正常工作并拥有正确的数据文件路径?
I made a research and found, the folder data
was create in the root of the virtualenv's folder that caused the error. How should I improve my code to keep my tests working and to have the correct path to the data file?
文件内容:
数据/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()
tests/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模块的新手.请帮助我解决这个问题.
I am new in packaging Python modules. Please help me with this issue.
================================================ =====================
=====================================================================
我发现我需要使用sys.prefix
来访问virtualenv的根目录.换句话说,如果我以这种方式编辑 mymodule .__ init __.py ,则一切将正常运行:
I figured out that I need to use sys.prefix
to access the virtualenv's root. In other words, if I edit mymodule.__init__.py this way everything will work correctly:
import os
import sys
src = os.path.join(sys.prefix, 'data/1.txt')
def get():
with open(src) as f:
return f.read().strip()
但是此后测试失败,并显示以下错误:
But after that the test fails with the error:
FileNotFoundError: [Errno 2] No such file or directory: '/usr/data/1.txt'
这是因为sys.prefix
是/usr
而没有激活的virtualenv.因此,我想我需要一种不同的方法来改善包装.
This is because sys.prefix
is /usr
without activated virtualenv. So I need a different way to improve the package, I guess.
推荐答案
-
在安装软件包时检查文件是否正确分发.
Check that your file is properly distributed when installing the package.
sys.prefix
将找不到您的"程序包.模块的__file__
属性指向__init__.py
文件.您可以将其用于基本路径,如下所示:
sys.prefix
will not locate "your" package. The __file__
attribute of the module points to the __init__.py
file. You can use this for the base path as in:
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()
这篇关于如何正确分配带有数据文件的pip包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!