如何从当前脚本上方的目录导入模块

发布于 2024-07-24 22:55:15 字数 651 浏览 1 评论 0原文

对于我的 Python 应用程序,我有以下目录结构:

\myapp
\myapp\utils\
\myapp\utils\GChartWrapper\
\myapp\model\
\myapp\view\
\myapp\controller\

\myapp\view\ 中的一个类必须导入一个名为 GChartWrapper。 但是,我收到导入错误...

myview.py
from myapp.utils.GChartWrapper import *

这是错误:

<type 'exceptions.ImportError'>: No module named GChartWrapper.GChart
      args = ('No module named GChartWrapper.GChart',)
      message = 'No module named GChartWrapper.GChart' 

我做错了什么? 我真的很难在Python中导入模块/类......

For my Python application, I have the following directories structure:

\myapp
\myapp\utils\
\myapp\utils\GChartWrapper\
\myapp\model\
\myapp\view\
\myapp\controller\

One of my class in \myapp\view\ must import a class called GChartWrapper. However, I am getting an import error...

myview.py
from myapp.utils.GChartWrapper import *

Here is the error:

<type 'exceptions.ImportError'>: No module named GChartWrapper.GChart
      args = ('No module named GChartWrapper.GChart',)
      message = 'No module named GChartWrapper.GChart' 

What am I doing wrong? I really have a hard time to import modules/classes in Python...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

岁月苍老的讽刺 2024-07-31 22:55:15

__init__.py GChartWrapper 包的 file 需要 PYTHONPATH 上的 GChartWrapper 包。 您可以从第一行看出:

from GChartWrapper.GChart import *

是否有必要将 GChartWrapper 包含在您的包目录结构中?
如果是这样,那么您可以做的一件事就是在运行时将包所在的路径添加到 sys.path 中。 我认为 myview.py 位于 myapp\view 目录中? 然后,您可以在导入 GChartWrapper 之前执行此操作:

import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))

如果不需要将其放在目录结构中,则将其安装在常规位置可能会更容易。 您可以通过运行 GChartWrapper 源代码发行版中包含的 setup.py 脚本来完成此操作。

The __init__.py file of the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line:

from GChartWrapper.GChart import *

Is it necessary to have the GChartWrapper included package in your package directory structure?
If so, then one thing you could do is adding the path where the package resides to sys.path at run time. I take it myview.py is in the myapp\view directory? Then you could do this before importing GChartWrapper:

import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))

If it is not necessary to have it in your directory structure, it could be easier to have it installed at the conventional location. You can do that by running the setup.py script that's included in the GChartWrapper source distribution.

哎呦我呸! 2024-07-31 22:55:15

您不能从任意路径导入模块和包。 相反,在 python 中,您使用包和绝对导入。 这将避免未来所有的问题。

示例:

创建以下文件:

MyApp\myapp\__init__.py
MyApp\myapp\utils\__init__.py
MyApp\myapp\utils\charts.py
MyApp\myapp\model\__init__.py
MyApp\myapp\view\__init__.py
MyApp\myapp\controller\__init__.py
MyApp\run.py
MyApp\setup.py
MyApp\README

除以下文件外,文件应为空:

MyApp\myapp\utils\charts.py:

class GChartWrapper(object):
    def __init__(self):
        print "DEBUG: An instance of GChartWrapper is being created!"

MyApp\myapp\ view\__init__.py:

from myapp.utils.charts import GChartWrapper

def start():
    c = GChartWrapper() # creating instance of the class

MyApp\run.py:

from myapp.view import start
start()

就这样! 当您运行入口点 (run.py) 时,它会调用视图上的函数,并创建 GChartWrapper 类的实例。 使用此结构,您可以在任何地方导入任何内容并使用它。

作为补充,您可以在 MyApp\setup.py 中为 MyApp\myapp 包编写安装程序。 使用 distutils 来编写它:

from distutils.core import setup
setup(name='MyApp',
      version='1.0',
      description='My Beautiful Application',
      author='Martin',
      author_email='[email protected]',
      url='http://stackoverflow.com/questions/1003843/',
      packages=['myapp'],
      scripts=['run.py']
     )

这就足够了。 现在,当人们下载 MyApp 文件夹时,他们只需使用 setup.py 安装它并使用 run.py 运行它。 Distutils 可以生成多种格式的包,包括 Windows 可安装的 .EXE

它是分发 python 包/应用程序的标准方式。

You don't import modules and packages from arbritary paths. Instead, in python you use packages and absolute imports. That'll avoid all future problems.

Example:

create the following files:

MyApp\myapp\__init__.py
MyApp\myapp\utils\__init__.py
MyApp\myapp\utils\charts.py
MyApp\myapp\model\__init__.py
MyApp\myapp\view\__init__.py
MyApp\myapp\controller\__init__.py
MyApp\run.py
MyApp\setup.py
MyApp\README

The files should be empty except for those:

MyApp\myapp\utils\charts.py:

class GChartWrapper(object):
    def __init__(self):
        print "DEBUG: An instance of GChartWrapper is being created!"

MyApp\myapp\view\__init__.py:

from myapp.utils.charts import GChartWrapper

def start():
    c = GChartWrapper() # creating instance of the class

MyApp\run.py:

from myapp.view import start
start()

That's all! When you run your entry point (run.py) it calls a function on the view, and that creates an instance of the GChartWrapper class. Using this structure you can import anything anywhere and use it.

To complement, in MyApp\setup.py you write an installation program for the MyApp\myapp package. Use distutils to write it:

from distutils.core import setup
setup(name='MyApp',
      version='1.0',
      description='My Beautiful Application',
      author='Martin',
      author_email='[email protected]',
      url='http://stackoverflow.com/questions/1003843/',
      packages=['myapp'],
      scripts=['run.py']
     )

That is enough. Now when people download the MyApp folder, they can just install it using setup.py and run it using run.py. Distutils can generate packages in a number of formats including windows installable .EXE

It's the standard way of distributing python packages/applications.

帝王念 2024-07-31 22:55:15

您可以更改 python 查找文件的路径。

在源文件的顶部添加:

import sys
sys.path.append("..") 

或者更改环境变量:

export PYTHONPATH=..

You can change the path where python looks for files.

At the top of your source file, add:

import sys
sys.path.append("..") 

Or alternatively change the environment variable:

export PYTHONPATH=..
陌路终见情 2024-07-31 22:55:15

或者从 python 2.5 开始(再次假设 myview 位于 myapp\view 中:

from __future__ import absolute_import
from ..utils.GChartWrapper import *

请参阅: http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

Or starting in python 2.5 (again assuming myview is in myapp\view:

from __future__ import absolute_import
from ..utils.GChartWrapper import *

See: http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

狼性发作 2024-07-31 22:55:15

GChartWrapper 也可以从 PyPI 获得,因此您可以使用 easy_install 或 pip 来安装该模块:

sudo pip install GChartWrapper==0.9

然后它将自动添加到您的 PYTHONPATH 中,然后您可以从 /myapp/utils 目录中将其删除。 如果您无法使用 sudo,请考虑使用 virtualenv(和 virtualenvwrapper)。

GChartWrapper is also available from PyPI so you can use easy_install or pip to install the module:

sudo pip install GChartWrapper==0.9

It will then be automatically added to your PYTHONPATH and then you can remove it from your /myapp/utils directory. If you can't use sudo, look at using virtualenv (and virtualenvwrapper).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文