在 Python 中导入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681366/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:41:49  来源:igfitidea点击:

Importing files in Python?

pythonfileimport

提问by Kaushik

How do I import Python files during execution?

如何在执行期间导入 Python 文件?

I have created 3 file a.py,b.pyand c.pyin a path C:\Users\qksr\Desktop\Samples

我创建了 3 个文件a.pyb.pyc.py在一个路径中C:\Users\qksr\Desktop\Samples

The files contain the code as shown below:

这些文件包含如下所示的代码:

a.py

一个.py

from c import MyGlobals

def func2():
    print MyGlobals.x
    MyGlobals.x = 2

b.py

b.py

import a
from c import MyGlobals

def func1():
    MyGlobals.x = 1      

if __name__ == "__main__":
    print MyGlobals.x
    func1()
    print MyGlobals.x
    a.func2()
    print MyGlobals.x

c.py

py

class MyGlobals(object):
    x = 0

When I execute the code b.py the following error is thrown:

当我执行代码 b.py 时抛出以下错误:

ImportError: No module named a

I believe my working directory is default and all the file a,b,c is just created by me in the samples folder.

我相信我的工作目录是默认的,所有文件 a、b、c 都是我在示例文件夹中创建的。

How do I import python files in Python?

如何在 Python 中导入 python 文件?

采纳答案by pradyunsg

If you are working in the same directory, that is, b.pyis in the same folder as a.py, I am unable to reproduce this problem (and do not know why this problem occurs), but it would be helpful if you post what os.getcwd()returns for b.py.

如果你是在同一个目录,也就是工作,b.py是在同一个文件夹中a.py,我不能重现这个问题(不知道为什么会出现这个问题),但是如果你发布的内容将是有益os.getcwd()的返回b.py

If that's not the case, add this on top of b.py

如果不是这种情况,请将其添加到 b.py

import sys
sys.path.append('PATH TO a.py')

OR if they are in the same path,

或者如果他们在同一条路上,

import sys
sys.path.append(os.basename(sys.argv[0])) # It should be there anyway but still..

回答by User

Referring to: I would like to know how to import a file which is created in any path outside the default path ?

参考:我想知道如何导入在默认路径之外的任何路径中创建的文件?

import sys

sys.path.append(directory_path) # a.py should be located here

回答by akaIDIOT

By default, Python won't import modules from the current working directory. There's 2 (maybe more) solutions for this:

默认情况下,Python 不会从当前工作目录导入模块。有 2 个(可能更多)解决方案:

PYTHONPATH=. python my_file.py

which tells python to look for modules to import in ., or:

它告诉 python 寻找要导入的模块.,或者:

sys.path.append(os.path.dirname(__file__))

which modifies the import path on runtime, adding the directory of the 'current' file.

它在运行时修改导入路径,添加“当前”文件的目录。

回答by Benoit

Tweaking PYTHONPATHis generally not a very good idea.

调整PYTHONPATH通常不是一个好主意。

A better way is to make your current directory behave like a module, by adding a file named __init__.py, which can be empty.

更好的方法是通过添加一个名为 的文件__init__.py,使您的当前目录表现得像一个模块,该文件可以为空。

Then the python interpretter allows you to import files from that directory.

然后python解释器允许您从该目录导入文件。

回答by Eric Leschinski

There are many ways to import a python file:

导入python文件的方法有很多:

Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.

不要草率地选择第一个适合您的导入策略,否则当您发现它不能满足您的需求时,您将不得不重新编写代码库。

I start out explaining the the easiest console example #1, then move toward the most professional and robust program example #5

我开始解释最简单的控制台示例 #1,然后转向最专业和最强大的程序示例 #5

Example 1, Import a python module with python interpreter:

示例 1,使用 python 解释器导入一个 python 模块:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print "vixens cry"
    
  2. Get into the python interpreter:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    You invoked the python function what_does_the_fox_say()from within the file foxthrough the python interpreter.

  1. 把它放在 /home/el/foo/fox.py 中:

    def what_does_the_fox_say():
      print "vixens cry"
    
  2. 进入python解释器:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    您通过 python 解释器what_does_the_fox_say()从文件中调用了 python 函数fox

Option 2, Use execfile in a script to execute the other python file in place:

选项 2,在脚本中使用 execfile 就地执行另一个 python 文件:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print "hi"
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

  1. 把它放在 /home/el/foo2/mylib.py 中:

    def moobar():
      print "hi"
    
  2. 把它放在 /home/el/foo2/main.py 中:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. 运行文件:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    moobar 函数是从 mylib.py 导入的,并在 main.py 中可用

Option 3, Use from ... import ... functionality:

选项 3,使用 from ... import ... 功能:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print "where are the nuclear wessels?"
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. Run it like this:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    If you defined other functions in chekov.py, they would not be available unless you import *

  1. 把它放在 /home/el/foo3/chekov.py 中:

    def question():
      print "where are the nuclear wessels?"
    
  2. 把它放在 /home/el/foo3/main.py 中:

    from chekov import question
    question()
    
  3. 像这样运行它:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    如果你在 chekov.py 中定义了其他函数,它们将不可用,除非你 import *

Option 4, Import riaa.py if it's in a different file location from where it is imported

选项 4,如果 riaa.py 与导入位置不同,则导入 riaa.py

  1. Put this in /home/el/foo4/bittorrent/riaa.py:

    def watchout_for_riaa_mpaa():
      print "there are honeypot kesha songs on bittorrent that log IP " +
      "addresses of seeders and leechers. Then comcast records strikes against " +
      "that user and thus, the free internet was transmogified into " +
      "a pay-per-view cable-tv enslavement device back in the 20th century."
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/bittorrent"))
    from riaa import *
    
    watchout_for_riaa_mpaa()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    there are honeypot kesha songs on bittorrent...
    

    That imports everything in the foreign file from a different directory.

  1. 把它放在 /home/el/foo4/bittorrent/riaa.py 中:

    def watchout_for_riaa_mpaa():
      print "there are honeypot kesha songs on bittorrent that log IP " +
      "addresses of seeders and leechers. Then comcast records strikes against " +
      "that user and thus, the free internet was transmogified into " +
      "a pay-per-view cable-tv enslavement device back in the 20th century."
    
  2. 把它放在 /home/el/foo4/main.py 中:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/bittorrent"))
    from riaa import *
    
    watchout_for_riaa_mpaa()
    
  3. 运行:

    el@apollo:/home/el/foo4$ python main.py 
    there are honeypot kesha songs on bittorrent...
    

    这会从不同的目录导入外部文件中的所有内容。

Option 5, Import files in python with the bare import command:

选项 5,使用裸导入命令在 python 中导入文件:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. Make an empty file named __init__.pyunder herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.pyfile:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.pyPut this in there:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. Run it:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!
    

    The empty __init__.pyfile communicates to the python interpreter that the developer intends this directory to be an importable package.

  1. 新建一个目录 /home/el/foo5/
  2. 新建一个目录 /home/el/foo5/herp
  3. 创建一个以__init__.pyherp命名的空文件:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. 创建一个新目录 /home/el/foo5/herp/derp

  5. 在derp下,创建另一个__init__.py文件:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. 在 /home/el/foo5/herp/derp 下创建一个名为yolo.pyPut this in there的新文件:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. 关键时刻,制作新文件/home/el/foo5/main.py,把它放在那里;

    from herp.derp.yolo import skycake
    skycake()
    
  8. 运行:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!
    

    __init__.py文件与 python 解释器通信,开发人员打算将此目录作为可导入包。

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131

如果您想查看我关于如何在目录下包含所有 .py 文件的帖子,请参见此处:https: //stackoverflow.com/a/20753073/445131

Bonus protip, whether you are using Mac, Linux or Windows, you need to be using python's idle editoras described here. It will unlock your python world. http://www.youtube.com/watch?v=DkW5CSZ_VII

额外提示,无论您使用的是 Mac、Linux 还是 Windows,您都需要使用此处所述的python 空闲编辑器。它将解锁您的 Python 世界。 http://www.youtube.com/watch?v=DkW5CSZ_VII

回答by Sarah Labbé

1st option:Add the path to your files to the default paths Pythons looks at.

第一个选项:将文件路径添加到 Pythons 查看的默认路径中。

import sys
sys.path.insert(0, 'C:/complete/path/to/my/directory')

2nd option:Add the path relative to your current root of your environment (current directory), using instead the following:

第二个选项:添加相对于当前环境根目录(当前目录)的路径,改为使用以下内容:

#Learn your current root 
import os
os.getcwd()  

#Change your current root (optional)
os.chdir('C:/new/root')

#Add the path from your current root '.' to your directory
import sys
sys.path.insert(0, './Path/from/current/root/to/my/directory')