在同一个包中导入Python脚本,使用在i中包含Python包名称的路径

2024-05-15 01:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python包(里面是empty\uu init\uu.py)和几个脚本,为了简化,我们称它为“mypackage”。然后,我有两个脚本,一个叫做“实用程序.py“,一个电话”视图.py". 我想在视图中导入utils,但是,根据我使用的计算机(都是Windows 10、都是WinPython、都是PyCharm、都是64位)的不同,只有一个导入窗体可以工作,来自以下两个:

import utils as u

或者

import mypackage.utils as u

为什么他们两个都不工作?你知道吗


Tags: pyimport实用程序脚本视图initwindowsas
2条回答

可能是因为您的一台计算机有python2.x,而另一台计算机有python3.x。在同一个包中导入模块的方式随PEP 328而改变。你知道吗

前一种方法是使用模糊的相对导入

import utils

问题是,这是指包中的模块还是stdlib模块?这种模糊性意味着在python3.0中,决定此语法将始终引用系统路径(称为绝对导入)和语法

from . import utils

为了应对这种向后不兼容的变化,python引入了

from __future__ import absolute_import

您可以在文件顶部放入python version>;=2.5代码,然后使用后一种方法。你知道吗

据我所知,import mypackage.utils应该可以工作,只要mypackagesys.path的目录中,所以我认为无论发生什么情况都应该可以工作。你知道吗

正如python文档中提到的:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  1. The directory containing the input script (or the current directory when no file is specified).
  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  3. The installation-dependent default.

在编写import mypackage.utils as u时,mypackage目录应该在PYTHONPATH环境变量中指定。你知道吗

相关问题 更多 >

    热门问题