从不同目录导入python包

2024-05-17 14:06:03 发布

您现在位置: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

从里面找东西

为此,我需要在哪里放置__init__.py文件(此时,“\something\python”路径被添加到my.tchsrc)

现在,我得到以下错误:

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

把它加到我的Python身上有问题吗?或者我该怎么解决?当前的解决方法是将decorators.py复制粘贴到我制作的每个新目录中(如果我制作了一个新版本的代码,比如“20131029”),但这只是一个愚蠢的解决方法,这意味着我每次制作新版本的代码时都要复制粘贴很多东西,所以我想要的是一个更优雅的版本和正确的导入。

注意:我在Python2.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/在这个列表中,所以我不明白为什么它不工作?


Tags: frompyimport版本目录decorators编辑extras
0条回答
网友
1楼 · 发布于 2024-05-17 14:06:03

您的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()

相关问题 更多 >