我正在创建一个程序包,首先我在本地安装它,python setup.py develop
我在调用程序时遇到问题
>>> import cstm.artefact as art
>>> art.what_is('Objname', 'en')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/guinsly/development/public/project/jeunesse/canadian_science_and_t
echnology_museum_api/cstm/artefact.py", line 56, in what_is
valeur = open_file(keywords, lang)
File "/home/guinsly/development/public/project/jeunesse/canadian_science_and_t
echnology_museum_api/cstm/artefact.py", line 24, in open_file
book = xlrd.open_workbook(path)
File "/usr/lib/python2.7/dist-packages/xlrd/__init__.py", line 394, in open_wo
rkbook
f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: '/home/guinsly/cstm/data/data.xls'
所以我要创建的程序包就在这条路径上 /home/guinsly/development/public/project/jeunesse/canadian_science_and_technology_museum_api/cstm/
但是程序包尝试.xls
在运行bpython
控制台时打开我所在的文件。
在我的包装上,我的测试还可以
-> % py.test -v
============================== test session starts ==============================
platform linux -- Python 3.4.0 -- py-1.4.26 -- pytest-2.6.4 -- /usr/bin/python3
plugins: quickcheck
collected 4 items
test_artefact.py::TestArtefact::test_definition PASSED
test_artefact.py::TestArtefact::test_definition_fr PASSED
test_artefact.py::TestArtefact::test_definition_not_found PASSED
test_artefact.py::TestArtefact::test_definition_not_found_fr PASSED
=========================== 4 passed in 0.09 seconds ============================
guinsly@guinsly-ThinkPad-L430 [09:46:33] [~/development/public/project/jeunesse/canadian_science_and_technology_museum_api]
问题:如何在此功能上正确设置路径
def open_file(keywords, lang = 'en'):
"""
Open and read an Excel file
"""
directory = os.getcwd()
path = directory+"/cstm/data/data.xls"
....
您正在使用相对于当前工作目录的路径,而不是相对于您的项目的路径。当前工作目录由用户设置(例如,基于其在终端中的当前位置)。
使用__file__
模块的全局变量来确定模块位置:
import os
module_path = os.path.dirname(os.path.abspath(__file__))
并建立相对于该文件的路径:
path = os.path.join(module_path, "cstm/data/data.xls")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句