从不同目录导入python包

使用死亡之星

我有以下目录结构:

\something\python\
    extras\
        __init__.py # empty file
        decorators.py # contains a benchmark decorator (and other things)
    20131029\   # not a package, this contains the scripts i use directly by doing "python somethingelse.py"
        somethingelse.py

现在我希望能够做类似的事情

from .extras import decorators
from decorators import benchmark

从somethingelse.py内部

为此,我需要在哪里放置__init__.py文件(目前,“ \ something \ python \”路径已添加到我的.tchsrc中)

现在,我得到以下错误:

 from .extras import decorators
ValueError: Attempted relative import in non-package

将其添加到我的pythonpath中是否有问题?还是应该解决这个问题?我当前的解决方法是仅将decorators.py复制粘贴到我创建的每个新目录中(如果我创建代码的新版本,例如“ 20131029”),但这只是一个愚蠢的解决方法,这意味着我必须复制粘贴每次我制作代码的新版本时都会有很多东西,因此我想要一个带有正确导入的更优雅的版本。

注意:我正在python 2.7中工作,如果有什么区别吗?

编辑:是的,我通过运行它

python somethingelse.py

更多编辑:不知道定义基准装饰器的方式是否重要?(它不是一个类或类似的类,接下来的事情正是来自decorators.py文件)

import time, functools
def benchmark(func):
    """
    A decorator that prints the time a function takes
    to execute.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t = time.time()
        res = func(*args, **kwargs)
        print func.__name__, time.time()-t
        return res
    return wrapper

编辑:如果我把\ something \ python \ extras \放到我的pythonpath中,我得到

ImportError: No module named decorators

当我跑步时:

from decorators import benchmark

这是否意味着我需要在该Extras目录中创建另一个子目录,而不是将decorators.py放在其中?

编辑:.tchsrc中,我添加了以下行:

setenv PYTHONPATH /bla/blabla/something/python/extras/

并在somethingelse.py中,如果我运行以下命令:

import sys
s = sys.path
for k in s:
    print k

我发现路径/ bla / blabla / something / python / extras /在该列表中,所以我不明白为什么它不起作用?

马丁·彼得斯(Martijn Pieters)

您的20131029目录不是软件包,因此您不能使用超出其的相对导入路径。

您可以extras使用当前脚本中的相对路径目录添加到Python模块搜索路径:

import sys, os

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

sys.path.insert(0, os.path.normpath(os.path.join(here, '../extras')))

现在导入extras首先目录中查找模块,因此请使用:

import decorators

因为您的目录名本身仅使用数字,所以无论如何您都不能将其打包软件包名称必须遵循Python标识符规则,该规则不能以数字开头。即使您重命名目录并添加了__init__.py文件,当您在目录中以脚本形式运行文件时,仍然不能将其作为包使用。脚本始终被视为位于程序包之外。您必须有一个顶级“ shim”脚本,该脚本从包中导入真实代码:

from package_20131029.somethingelse import main

main()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章