从相对路径导入模块

时间:2021-03-15 13:13:10

How do I import a Python module given its relative path?

如何导入给定相对路径的Python模块?

For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py?

例如,如果dirFoo包含Foo。py和dirBar包含Bar。py,如何导入Bar。py Foo.py ?

Here's a visual representation:

这里有一个可视化表示:

dirFoo\
    Foo.py
    dirBar\
        Bar.py

Foo wishes to include Bar, but restructuring the folder hierarchy is not an option.

Foo希望包含Bar,但是重组文件夹层次结构不是一个选项。

22 个解决方案

#1


312  

Assuming that both your directories are real Python packages (do have the __init__.py file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.

假设您的两个目录都是真正的Python包(请使用__init__。在它们里面的py文件),这里有一个相对于脚本位置包含模块的安全解决方案。

I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.

我假设您希望这样做,因为您需要在脚本中包含一组模块。我在多个产品中使用这个功能,并在许多特殊场景中使用:从另一个目录调用的脚本,或者用python执行,而不是打开新的解释器。

 import os, sys, inspect
 # realpath() will make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # Use this if you want to include modules from a subfolder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if the script is called in different ways on Windows.
 # __file__ fails if someone does os.chdir() before.
 # sys.argv[0] also fails, because it doesn't not always contains the path.

As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.

另外,这种方法还可以强制Python使用模块,而不是安装在系统上的模块。

Warning! I don't really know what is happening when current module is inside an egg file. It probably fails too.

警告!我不知道当前模块在egg文件中会发生什么。它也可能失败。

#2


315  

Be sure that dirBar has the __init__.py file -- this makes a directory into a Python package.

一定要确保dirBar有__init__。py文件——这使一个目录成为一个Python包。

#3


244  

You could also add the subdirectory to your Python path so that it imports as a normal script.

您还可以将子目录添加到Python路径中,以便将其作为常规脚本导入。

import sys
sys.path.insert(0, <path to dirFoo>)
import Bar

#4


108  

import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

#5


94  

Just do simple things to import the .py file from a different folder.

只需做一些简单的事情,从另一个文件夹导入.py文件。

Let's say you have a directory like:

假设您有一个目录,如:

lib/abc.py

Then just keep an empty file in lib folder as named

然后在lib文件夹中保留一个名为的空文件

__init__.py

And then use

然后使用

from lib.abc import <Your Module name>

Keep the __init__.py file in every folder of the hierarchy of the import module.

保持__init__。导入模块层次结构的每个文件夹中的py文件。

#6


77  

If you structure your project this way:

如果你的项目结构是这样的:

src\
  __init__.py
  main.py
  dirFoo\
    __init__.py
    Foo.py
  dirBar\
    __init__.py
    Bar.py

Then from Foo.py you should be able to do:

然后从Foo。你应该能够做到:

import dirFoo.Foo

Or:

或者:

from dirFoo.Foo import FooObject

Per Tom's comment, this does require that the src folder is accessible either via site_packages or your search path. Also, as he mentions, __init__.py is implicitly imported when you first import a module in that package/directory. Typically __init__.py is simply an empty file.

根据Tom的评论,这确实要求可以通过site_packages或您的搜索路径访问src文件夹。而且,正如他所提到的,……当您第一次导入包/目录中的模块时,将隐式地导入py。通常__init__。py只是一个空文件。

#7


44  

The easiest method is to use sys.path.append().

最简单的方法是使用sys.path.append()。

However, you may be also interested in the imp module. It provides access to internal import functions.

但是,您可能也对imp模块感兴趣。它提供对内部导入功能的访问。

# mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file 

This can be used to load modules dynamically when you don't know a module's name.

当您不知道模块的名称时,可以使用它动态地加载模块。

I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.

在过去,我使用过这个方法来为应用程序创建一个插件类型的接口,在这个应用程序中,用户可以编写带有应用程序特定功能的脚本,并在一个特定的目录中删除他们的脚本。

Also, these functions may be useful:

此外,这些职能可能有用:

imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)

#8


40  

This is the relevant PEP:

这是相关的PEP:

http://www.python.org/dev/peps/pep-0328/

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

特别是,假设dirFoo是dirBar上的目录…

In dirFoo\Foo.py:

在dirFoo \ Foo.py:

from ..dirBar import Bar

#9


20  

The easiest way without any modification to your script is to set PYTHONPATH environment variable. Because sys.path is initialized from these locations:

不修改脚本的最简单方法是设置PYTHONPATH环境变量。因为系统。从这些位置初始化路径:

  1. The directory containing the input script (or the current directory).
  2. 包含输入脚本(或当前目录)的目录。
  3. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  4. python路径(目录名的列表,与shell变量路径具有相同的语法)。
  5. The installation-dependent default.
  6. installation-dependent默认。

Just run:

运行:

export PYTHONPATH=/absolute/path/to/your/module

You sys.path will contains above path, as show below:

你的系统。路径将包含上述路径,如下所示:

print sys.path

['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']

#10


11  

In my opinion the best choice is to put __ init __.py in the folder and call the file with

在我看来,最好的选择是投入。py在文件夹中并调用该文件。

from dirBar.Bar import *

It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.

不建议使用sys.path.append(),因为如果使用与现有python包相同的文件名,可能会出错。我还没有对它进行测试,但那将是模糊的。

#11


10  

The quick-and-dirty way for Linux users

If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.

如果您只是随意修改,不关心部署问题,您可以使用一个符号链接(假设您的文件系统支持它),使模块或包可以直接在请求模块的文件夹中可见。

ln -s (path)/module_name.py

or

ln -s (path)/package_name

Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file __init__.py (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the import command.

注意:“模块”是任何扩展名为.py的文件,“包”是任何包含文件__init__的文件夹。py(可以是一个空文件)。从使用的角度来看,模块和包是相同的——它们都公开它们所包含的“定义和语句”,这是通过import命令请求的。

See: http://docs.python.org/2/tutorial/modules.html

参见:http://docs.python.org/2/tutorial/modules.html

#12


9  

from .dirBar import Bar

instead of:

而不是:

from dirBar import Bar

just in case there could be another dirBar installed and confuse a foo.py reader.

以防万一有另一个dirBar被安装并且混淆了一个foo。py读者。

#13


7  

For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:

对于这种情况,导入Bar。py Foo。py,首先我将这些文件夹转换成Python包,如下所示:

dirFoo\
    __init__.py
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then I would do it like this in Foo.py:

然后用fooy。py:

from .dirBar import Bar

If I wanted the namespacing to look like Bar.whatever, or

如果我想让名称空间看起来像Bar。无论如何,或

from . import dirBar

If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.

如果我想要有名字空间的酒吧。如果在dirBar包下有更多的模块,那么第二种情况将非常有用。

#14


6  

Add an __init__.py file:

添加一个__init__。py文件:

dirFoo\
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then add this code to the start of Foo.py:

然后将此代码添加到Foo.py的开头。

import sys
sys.path.append('dirBar')
import Bar

#15


5  

Relative sys.path example:

相对的系统。路径的例子:

# /lib/my_module.py
# /src/test.py


if __name__ == '__main__' and __package__ is None:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module

Based on this answer.

在此基础上回答。

#16


4  

Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them.

正如你提到的,通常你想要访问一个文件夹你的模块相对于你的主脚本运行的地方,所以你只需要导入它们。

Solution:

解决方案:

I have the script in D:/Books/MyBooks.py and some modules (like oldies.py). I need to import from subdirectory D:/Books/includes:

我的脚本在D:/Books/MyBooks中。py和一些模块(比如oldies.py)。我需要从子目录D:/Books/include:

import sys,site
site.addsitedir(sys.path[0] + '\\includes')
print (sys.path)  # Just verify it is there
import oldies

Place a print('done') in oldies.py, so you verify everything is going OK. This way always works because by the Python definition sys.path as initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

在旧版本中放置一个打印(“完成”)。py,验证一切正常。这种方法总是有效的,因为根据Python定义系统。在程序启动时初始化的路径,此列表的第一项path[0]是包含用于调用Python解释器的脚本的目录。

If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

如果脚本目录不可用(例如,如果交互调用解释器或从标准输入中读取脚本),路径[0]是空字符串,它将引导Python首先搜索当前目录中的模块。注意,在作为python路径的结果插入的条目之前插入脚本目录。

#17


3  

Another solution would be to install the py-require package and then use the following in Foo.py

另一个解决方案是安装py-require包,然后在Foo.py中使用以下内容

import require
Bar = require('./dirBar/Bar')

#18


2  

Look at the pkgutil module from the standard library. It may help you do what you want.

从标准库中查看pkgutil模块。它可以帮助你做你想做的事。

#19


2  

Here's a way to import a file from one level above, using the relative path.

这里有一种方法,可以使用相对路径从上面的一个级别导入文件。

Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.

基本上,只需将工作目录向上移动一个级别(或任何相关位置),将其添加到您的路径中,然后将工作目录移回它开始的位置。

#to import from one level above:
cwd = os.getcwd()
os.chdir("..")
below_path =  os.getcwd()
sys.path.append(below_path)
os.chdir(cwd)

#20


2  

Simply you can use: from Desktop.filename import something

您可以使用:从桌面。文件名进口的东西

Example:

例子:

given that the file is name test.py in directory Users/user/Desktop , and will import everthing.

假设文件是name test。py在目录用户/用户/桌面,并将导入所有内容。

the code:

代码:

from Desktop.test import *

But make sure you make an empty file called "__init__.py" in that directory

但是要确保你制作了一个名为“__init__”的空文件。py”目录

#21


0  

I'm not experienced about python, so if there is any wrong in my words, just tell me. If your file hierarchy arranged like this:

我对python没有经验,所以如果我的话有什么错,请告诉我。如果您的文件层次结构是这样排列的:

project\
    module_1.py 
    module_2.py

module_1.py defines a function called func_1(), module_2.py:

module_1。py定义了一个函数func_1(), module_2.py:

from module_1 import func_1

def func_2():
    func_1()

if __name__ == '__main__':
    func_2()

and you run python module_2.py in cmd, it will do run what func_1() defines. That's usually how we import same hierarchy files. But when you write from .module_1 import func_1 in module_2.py, python interpreter will say No module named '__main__.module_1'; '__main__' is not a package. So to fix this, we just keep the change we just make, and move both of the module to a package, and make a third module as a caller to run module_2.py.

运行python module_2。在cmd中,它将运行func_1()定义的函数。这通常是我们导入相同层次结构文件的方式。但是当您从。module_1中写入时,在module_2中导入func_1。py, python解释器会说没有名为“__main__.module_1”的模块;“__main__”不是一个包。为了解决这个问题,我们只保留我们刚刚做的更改,并将两个模块移动到一个包中,并使第三个模块作为调用者运行module_2.py。

project\
    package_1\
        module_1.py
        module_2.py
    main.py

main.py:

main.py:

from package_1.module_2 import func_2

def func_3():
    func_2()

if __name__ == '__main__':
    func_3()

But the reason we add a . before module_1 in module_2.py is that if we don't do that and run main.py, python interpreter will say No module named 'module_1', that's a little tricky, module_1.py is right beside module_2.py. Now I let func_1() in module_1.py do something:

我们加a的原因。在module_2 module_1之前。如果我们不这样做,运行main。py, python解释器会说没有模块叫做'module_1',这有点棘手,module_1。py就在module_2。py旁边。现在我让函数1()在module_1中。py做某事:

def func_1():
    print(__name__)

that __name__ records who calls func_1. Now we keep the . before module_1 , run main.py, it will print package_1.module_1, not module_1. It indicates that the one who calls func_1() is at the same hierarchy as main.py, the . imply that module_1 is at the same hierarchy as module_2.py itself. So if there isn't a dot, main.py will recognize module_1 at the same hierarchy as itself, it can recognize package_1, but not what "under" it.

那个__name__记录谁调用func_1。现在我们保持。在module_1之前,运行main。py,它将打印package_1。module_1,不是module_1。它指示调用func_1()的对象与main处于相同的层次结构。py,。暗示module_1与module_2处于相同的层次结构。py本身。所以如果没有点,main。py将在与自己相同的层次结构中识别module_1,它可以识别package_1,但不能识别“在”下的内容。

Now let's make it a bit complicated. You have a config.ini and a module defines a function to read it at the same hierarchy as 'main.py'.

现在让我们把它变得有点复杂。你有一个配置。ini和一个模块定义了一个函数,用于在与“main.py”相同的层次上读取它。

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
    main.py

And for some unavoidable reason, you have to call it with module_2.py, so it has to import from upper hierarchy.module_2.py:

由于某种不可避免的原因,你必须用module_2来称呼它。因此,它必须从上层层次导入。

 import ..config
 pass

Two dots means import from upper hierarchy (three dots access upper than upper,and so on). Now we run main.py, the interpreter will say:ValueError:attempted relative import beyond top-level package. The "top-level package" at here is main.py. Just because config.py is beside main.py, they are at same hierarchy, config.py isn't "under" main.py, or it isn't "leaded" by main.py, so it is beyond main.py. To fix this, the simplest way is:

两个点表示从上层层次导入(三个点访问上层而不是上层,依此类推)。现在我们主要运行。py,解释器会说:ValueError:试图在*包之外进行相对导入。这里的“*包”是main.py。因为配置。py是主要的旁边。py,它们在相同的层次结构中。py并不是“下”的主要。py,或者它不是由main引导的。py,所以它超出了mainpy。要解决这个问题,最简单的方法是:

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
main.py

I think that is coincide with the principle of arrange project file hierarchy, you should arrange modules with different function in different folders, and just leave a top caller in the outside, and you can import how ever you want.

我认为这符合安排项目文件层级的原则,你应该在不同的文件夹中安排功能不同的模块,只在外部留下一个*调用者,你可以任意导入。

#22


-14  

Call me overly cautious, but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use Linux so mine would look like this:

你可以说我过于谨慎,但我喜欢让我的文件更便于携带,因为假设文件总是在每台计算机上的同一个位置是不安全的。我个人让代码先查找文件路径。我使用Linux,所以我的应该是这样的:

import os, sys
from subprocess import Popen, PIPE
try:
    path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]
    if not sys.path.__contains__(path):
        sys.path.append(path)
except IndexError:
    raise RuntimeError("You must have FILE to run this program!")

That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.

当然,除非你打算把它们打包在一起。但如果是这样的话,你也不需要两个单独的文件。

#1


312  

Assuming that both your directories are real Python packages (do have the __init__.py file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.

假设您的两个目录都是真正的Python包(请使用__init__。在它们里面的py文件),这里有一个相对于脚本位置包含模块的安全解决方案。

I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.

我假设您希望这样做,因为您需要在脚本中包含一组模块。我在多个产品中使用这个功能,并在许多特殊场景中使用:从另一个目录调用的脚本,或者用python执行,而不是打开新的解释器。

 import os, sys, inspect
 # realpath() will make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # Use this if you want to include modules from a subfolder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if the script is called in different ways on Windows.
 # __file__ fails if someone does os.chdir() before.
 # sys.argv[0] also fails, because it doesn't not always contains the path.

As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.

另外,这种方法还可以强制Python使用模块,而不是安装在系统上的模块。

Warning! I don't really know what is happening when current module is inside an egg file. It probably fails too.

警告!我不知道当前模块在egg文件中会发生什么。它也可能失败。

#2


315  

Be sure that dirBar has the __init__.py file -- this makes a directory into a Python package.

一定要确保dirBar有__init__。py文件——这使一个目录成为一个Python包。

#3


244  

You could also add the subdirectory to your Python path so that it imports as a normal script.

您还可以将子目录添加到Python路径中,以便将其作为常规脚本导入。

import sys
sys.path.insert(0, <path to dirFoo>)
import Bar

#4


108  

import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)

import mymodule

#5


94  

Just do simple things to import the .py file from a different folder.

只需做一些简单的事情,从另一个文件夹导入.py文件。

Let's say you have a directory like:

假设您有一个目录,如:

lib/abc.py

Then just keep an empty file in lib folder as named

然后在lib文件夹中保留一个名为的空文件

__init__.py

And then use

然后使用

from lib.abc import <Your Module name>

Keep the __init__.py file in every folder of the hierarchy of the import module.

保持__init__。导入模块层次结构的每个文件夹中的py文件。

#6


77  

If you structure your project this way:

如果你的项目结构是这样的:

src\
  __init__.py
  main.py
  dirFoo\
    __init__.py
    Foo.py
  dirBar\
    __init__.py
    Bar.py

Then from Foo.py you should be able to do:

然后从Foo。你应该能够做到:

import dirFoo.Foo

Or:

或者:

from dirFoo.Foo import FooObject

Per Tom's comment, this does require that the src folder is accessible either via site_packages or your search path. Also, as he mentions, __init__.py is implicitly imported when you first import a module in that package/directory. Typically __init__.py is simply an empty file.

根据Tom的评论,这确实要求可以通过site_packages或您的搜索路径访问src文件夹。而且,正如他所提到的,……当您第一次导入包/目录中的模块时,将隐式地导入py。通常__init__。py只是一个空文件。

#7


44  

The easiest method is to use sys.path.append().

最简单的方法是使用sys.path.append()。

However, you may be also interested in the imp module. It provides access to internal import functions.

但是,您可能也对imp模块感兴趣。它提供对内部导入功能的访问。

# mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file 

This can be used to load modules dynamically when you don't know a module's name.

当您不知道模块的名称时,可以使用它动态地加载模块。

I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.

在过去,我使用过这个方法来为应用程序创建一个插件类型的接口,在这个应用程序中,用户可以编写带有应用程序特定功能的脚本,并在一个特定的目录中删除他们的脚本。

Also, these functions may be useful:

此外,这些职能可能有用:

imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)

#8


40  

This is the relevant PEP:

这是相关的PEP:

http://www.python.org/dev/peps/pep-0328/

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

特别是,假设dirFoo是dirBar上的目录…

In dirFoo\Foo.py:

在dirFoo \ Foo.py:

from ..dirBar import Bar

#9


20  

The easiest way without any modification to your script is to set PYTHONPATH environment variable. Because sys.path is initialized from these locations:

不修改脚本的最简单方法是设置PYTHONPATH环境变量。因为系统。从这些位置初始化路径:

  1. The directory containing the input script (or the current directory).
  2. 包含输入脚本(或当前目录)的目录。
  3. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  4. python路径(目录名的列表,与shell变量路径具有相同的语法)。
  5. The installation-dependent default.
  6. installation-dependent默认。

Just run:

运行:

export PYTHONPATH=/absolute/path/to/your/module

You sys.path will contains above path, as show below:

你的系统。路径将包含上述路径,如下所示:

print sys.path

['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']

#10


11  

In my opinion the best choice is to put __ init __.py in the folder and call the file with

在我看来,最好的选择是投入。py在文件夹中并调用该文件。

from dirBar.Bar import *

It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.

不建议使用sys.path.append(),因为如果使用与现有python包相同的文件名,可能会出错。我还没有对它进行测试,但那将是模糊的。

#11


10  

The quick-and-dirty way for Linux users

If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.

如果您只是随意修改,不关心部署问题,您可以使用一个符号链接(假设您的文件系统支持它),使模块或包可以直接在请求模块的文件夹中可见。

ln -s (path)/module_name.py

or

ln -s (path)/package_name

Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file __init__.py (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the import command.

注意:“模块”是任何扩展名为.py的文件,“包”是任何包含文件__init__的文件夹。py(可以是一个空文件)。从使用的角度来看,模块和包是相同的——它们都公开它们所包含的“定义和语句”,这是通过import命令请求的。

See: http://docs.python.org/2/tutorial/modules.html

参见:http://docs.python.org/2/tutorial/modules.html

#12


9  

from .dirBar import Bar

instead of:

而不是:

from dirBar import Bar

just in case there could be another dirBar installed and confuse a foo.py reader.

以防万一有另一个dirBar被安装并且混淆了一个foo。py读者。

#13


7  

For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:

对于这种情况,导入Bar。py Foo。py,首先我将这些文件夹转换成Python包,如下所示:

dirFoo\
    __init__.py
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then I would do it like this in Foo.py:

然后用fooy。py:

from .dirBar import Bar

If I wanted the namespacing to look like Bar.whatever, or

如果我想让名称空间看起来像Bar。无论如何,或

from . import dirBar

If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.

如果我想要有名字空间的酒吧。如果在dirBar包下有更多的模块,那么第二种情况将非常有用。

#14


6  

Add an __init__.py file:

添加一个__init__。py文件:

dirFoo\
    Foo.py
    dirBar\
        __init__.py
        Bar.py

Then add this code to the start of Foo.py:

然后将此代码添加到Foo.py的开头。

import sys
sys.path.append('dirBar')
import Bar

#15


5  

Relative sys.path example:

相对的系统。路径的例子:

# /lib/my_module.py
# /src/test.py


if __name__ == '__main__' and __package__ is None:
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module

Based on this answer.

在此基础上回答。

#16


4  

Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them.

正如你提到的,通常你想要访问一个文件夹你的模块相对于你的主脚本运行的地方,所以你只需要导入它们。

Solution:

解决方案:

I have the script in D:/Books/MyBooks.py and some modules (like oldies.py). I need to import from subdirectory D:/Books/includes:

我的脚本在D:/Books/MyBooks中。py和一些模块(比如oldies.py)。我需要从子目录D:/Books/include:

import sys,site
site.addsitedir(sys.path[0] + '\\includes')
print (sys.path)  # Just verify it is there
import oldies

Place a print('done') in oldies.py, so you verify everything is going OK. This way always works because by the Python definition sys.path as initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

在旧版本中放置一个打印(“完成”)。py,验证一切正常。这种方法总是有效的,因为根据Python定义系统。在程序启动时初始化的路径,此列表的第一项path[0]是包含用于调用Python解释器的脚本的目录。

If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

如果脚本目录不可用(例如,如果交互调用解释器或从标准输入中读取脚本),路径[0]是空字符串,它将引导Python首先搜索当前目录中的模块。注意,在作为python路径的结果插入的条目之前插入脚本目录。

#17


3  

Another solution would be to install the py-require package and then use the following in Foo.py

另一个解决方案是安装py-require包,然后在Foo.py中使用以下内容

import require
Bar = require('./dirBar/Bar')

#18


2  

Look at the pkgutil module from the standard library. It may help you do what you want.

从标准库中查看pkgutil模块。它可以帮助你做你想做的事。

#19


2  

Here's a way to import a file from one level above, using the relative path.

这里有一种方法,可以使用相对路径从上面的一个级别导入文件。

Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.

基本上,只需将工作目录向上移动一个级别(或任何相关位置),将其添加到您的路径中,然后将工作目录移回它开始的位置。

#to import from one level above:
cwd = os.getcwd()
os.chdir("..")
below_path =  os.getcwd()
sys.path.append(below_path)
os.chdir(cwd)

#20


2  

Simply you can use: from Desktop.filename import something

您可以使用:从桌面。文件名进口的东西

Example:

例子:

given that the file is name test.py in directory Users/user/Desktop , and will import everthing.

假设文件是name test。py在目录用户/用户/桌面,并将导入所有内容。

the code:

代码:

from Desktop.test import *

But make sure you make an empty file called "__init__.py" in that directory

但是要确保你制作了一个名为“__init__”的空文件。py”目录

#21


0  

I'm not experienced about python, so if there is any wrong in my words, just tell me. If your file hierarchy arranged like this:

我对python没有经验,所以如果我的话有什么错,请告诉我。如果您的文件层次结构是这样排列的:

project\
    module_1.py 
    module_2.py

module_1.py defines a function called func_1(), module_2.py:

module_1。py定义了一个函数func_1(), module_2.py:

from module_1 import func_1

def func_2():
    func_1()

if __name__ == '__main__':
    func_2()

and you run python module_2.py in cmd, it will do run what func_1() defines. That's usually how we import same hierarchy files. But when you write from .module_1 import func_1 in module_2.py, python interpreter will say No module named '__main__.module_1'; '__main__' is not a package. So to fix this, we just keep the change we just make, and move both of the module to a package, and make a third module as a caller to run module_2.py.

运行python module_2。在cmd中,它将运行func_1()定义的函数。这通常是我们导入相同层次结构文件的方式。但是当您从。module_1中写入时,在module_2中导入func_1。py, python解释器会说没有名为“__main__.module_1”的模块;“__main__”不是一个包。为了解决这个问题,我们只保留我们刚刚做的更改,并将两个模块移动到一个包中,并使第三个模块作为调用者运行module_2.py。

project\
    package_1\
        module_1.py
        module_2.py
    main.py

main.py:

main.py:

from package_1.module_2 import func_2

def func_3():
    func_2()

if __name__ == '__main__':
    func_3()

But the reason we add a . before module_1 in module_2.py is that if we don't do that and run main.py, python interpreter will say No module named 'module_1', that's a little tricky, module_1.py is right beside module_2.py. Now I let func_1() in module_1.py do something:

我们加a的原因。在module_2 module_1之前。如果我们不这样做,运行main。py, python解释器会说没有模块叫做'module_1',这有点棘手,module_1。py就在module_2。py旁边。现在我让函数1()在module_1中。py做某事:

def func_1():
    print(__name__)

that __name__ records who calls func_1. Now we keep the . before module_1 , run main.py, it will print package_1.module_1, not module_1. It indicates that the one who calls func_1() is at the same hierarchy as main.py, the . imply that module_1 is at the same hierarchy as module_2.py itself. So if there isn't a dot, main.py will recognize module_1 at the same hierarchy as itself, it can recognize package_1, but not what "under" it.

那个__name__记录谁调用func_1。现在我们保持。在module_1之前,运行main。py,它将打印package_1。module_1,不是module_1。它指示调用func_1()的对象与main处于相同的层次结构。py,。暗示module_1与module_2处于相同的层次结构。py本身。所以如果没有点,main。py将在与自己相同的层次结构中识别module_1,它可以识别package_1,但不能识别“在”下的内容。

Now let's make it a bit complicated. You have a config.ini and a module defines a function to read it at the same hierarchy as 'main.py'.

现在让我们把它变得有点复杂。你有一个配置。ini和一个模块定义了一个函数,用于在与“main.py”相同的层次上读取它。

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
    main.py

And for some unavoidable reason, you have to call it with module_2.py, so it has to import from upper hierarchy.module_2.py:

由于某种不可避免的原因,你必须用module_2来称呼它。因此,它必须从上层层次导入。

 import ..config
 pass

Two dots means import from upper hierarchy (three dots access upper than upper,and so on). Now we run main.py, the interpreter will say:ValueError:attempted relative import beyond top-level package. The "top-level package" at here is main.py. Just because config.py is beside main.py, they are at same hierarchy, config.py isn't "under" main.py, or it isn't "leaded" by main.py, so it is beyond main.py. To fix this, the simplest way is:

两个点表示从上层层次导入(三个点访问上层而不是上层,依此类推)。现在我们主要运行。py,解释器会说:ValueError:试图在*包之外进行相对导入。这里的“*包”是main.py。因为配置。py是主要的旁边。py,它们在相同的层次结构中。py并不是“下”的主要。py,或者它不是由main引导的。py,所以它超出了mainpy。要解决这个问题,最简单的方法是:

project\
    package_1\
        module_1.py
        module_2.py
    config.py
    config.ini
main.py

I think that is coincide with the principle of arrange project file hierarchy, you should arrange modules with different function in different folders, and just leave a top caller in the outside, and you can import how ever you want.

我认为这符合安排项目文件层级的原则,你应该在不同的文件夹中安排功能不同的模块,只在外部留下一个*调用者,你可以任意导入。

#22


-14  

Call me overly cautious, but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use Linux so mine would look like this:

你可以说我过于谨慎,但我喜欢让我的文件更便于携带,因为假设文件总是在每台计算机上的同一个位置是不安全的。我个人让代码先查找文件路径。我使用Linux,所以我的应该是这样的:

import os, sys
from subprocess import Popen, PIPE
try:
    path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]
    if not sys.path.__contains__(path):
        sys.path.append(path)
except IndexError:
    raise RuntimeError("You must have FILE to run this program!")

That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.

当然,除非你打算把它们打包在一起。但如果是这样的话,你也不需要两个单独的文件。