python 如何从当前脚本以上级别的目录中导入模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1003843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import a module from a directory on level above the current script
提问by Martin
For my Python application, I have the following directories structure:
对于我的 Python 应用程序,我有以下目录结构:
\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...
我在 \myapp\view\ 中的一个类必须导入一个名为GChartWrapper的类。但是,我收到导入错误...
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...
我究竟做错了什么?我真的很难在 Python 中导入模块/类...
采纳答案by Steef
The __init__.py
fileof the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line:
GChartWrapper 包的__init__.py
文件需要 PYTHONPATH 上的 GChartWrapper 包。您可以通过第一行判断:
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
:
是否有必要在包目录结构中包含 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')))
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.
如果不需要将它放在您的目录结构中,将它安装在常规位置可能会更容易。您可以通过运行 GChartWrapper 源代码分发中包含的 setup.py 脚本来实现。
回答by nosklo
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.
您不会从任意路径导入模块和包。相反,在 python 中,您使用包和绝对导入。这将避免所有未来的问题。
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:
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:
MyApp\myapp\view\__init__.py:
from myapp.utils.charts import GChartWrapper
def start():
c = GChartWrapper() # creating instance of the class
MyApp\run.py:
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.
就这样!当您运行入口点 ( run.py
) 时,它会调用视图上的一个函数,并创建 GChartWrapper 类的实例。使用此结构,您可以在任何地方导入任何内容并使用它。
To complement, in MyApp\setup.py
you write an installation program for the MyApp\myapp package. Use distutilsto write it:
作为补充,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']
)
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
足够了。现在,当人们下载 MyApp 文件夹时,他们可以使用 setup.py 安装它并使用 run.py 运行它。Distutils 可以生成多种格式的包,包括 Windows 可安装的 .EXE
It's the standard way of distributing python packages/applications.
这是分发 python 包/应用程序的标准方式。
回答by DopplerShift
Or starting in python 2.5 (again assuming myview is in myapp\view:
或者从 python 2.5 开始(再次假设 myview 在 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
请参阅:http: //docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports
回答by Johan
You can change the path where python looks for files.
您可以更改 python 查找文件的路径。
At the top of your source file, add:
在源文件的顶部,添加:
import sys
sys.path.append("..")
Or alternatively change the environment variable:
或者更改环境变量:
export PYTHONPATH=..
回答by justquick
GChartWrapper is also available from PyPI so you can use easy_install or pip to install the module:
GChartWrapper 也可从 PyPI 获得,因此您可以使用 easy_install 或 pip 来安装模块:
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).
然后它会自动添加到您的 PYTHONPATH 中,然后您可以将其从 /myapp/utils 目录中删除。如果您不能使用 sudo,请查看使用 virtualenv(和 virtualenvwrapper)。