我有一个要分发的包:
mymodule/
data/
1.txt
mymodule/
__init__.py
tests/
test_mymodule.py
setup.py
为了将其安装在 virtualenv 下,我应用以下命令:
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
是在导致错误的 virtualenvs 文件夹的根目录中创建的。我应该如何改进我的代码以保持测试正常运行并拥有数据文件的正确路径?
文件内容:
数据/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
is /usr
没有激活 virtualenv。所以我想我需要一种不同的方式来改进这个包。