如何在python包中设置路径

时间:2015-02-15 02:55:35

标签: python package

我正在创建package,首先我在本地安装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"

....

1 个答案:

答案 0 :(得分:3)

您正在使用相对于当前工作目录的路径,而不是相对于您的项目。当前工作目录由用户设置(例如,基于其在终端中的当前位置)。

使用模块的__file__全局模块确定模块位置:

import os

module_path = os.path.dirname(os.path.abspath(__file__))

并将文件路径相对于:

path = os.path.join(module_path, "cstm/data/data.xls")