简体   繁体   English

导入Python文件[ModuleNotFound]

[英]Import Python file [ModuleNotFound]

I'm importing helpers.py file from <project_root>/lib/helpers.py location to one of the sub-folder in my project. 我正在从<project_root>/lib/helpers.py位置将helpers.py文件导入项目中的子文件夹之一。 I am using sys package. 我正在使用sys软件包。 But I'm getting ModuleNotFound error while importing. 但是我在导入时收到ModuleNotFound错误。

Given below is the code I'm using. 下面给出的是我正在使用的代码。

import sys
sys.path.insert(0, '/d/Development/s5-data-analysis/lib/')
import helpers

The sub-folder is /d/Development/s5-data-analysis/notebooks/my.ipynb . 子文件夹是/d/Development/s5-data-analysis/notebooks/my.ipynb What is the correct way of importing this helper.py to my.ipnb . 什么是导入此的正确方法helper.pymy.ipnb

This looks to me like you are using Git Bash on Windows (or some other Unix-Windows-Layer), which has its own builtin path translation. 在我看来,这就像您在Windows(或其他Unix-Windows-Layer)上使用Git Bash一样,它具有自己的内置路径转换。 Other programs like will only be able to use the usual path names, in this case d:\\Development\\s5-data-analysis\\lib : 其他类似的程序将只能使用常规的路径名,在这种情况下为d:\\Development\\s5-data-analysis\\lib

sys.path.insert(0, r"d:\Development\s5-data-analysis\lib")

You can convert lib folder into a package, by adding __init__.py to lib folder. 通过将__init__.py添加到lib文件夹,可以将lib文件夹转换为软件包。 In this file, you can import helpers module like this: 在此文件中,您可以这样导入helpers模块:

from . import helpers

Finally, on your actual codefile, import helpers module like this: 最后,在您的实际代码文件上,导入导入器模块,如下所示:

from lib import helpers

There are various ways through which you can import. 您可以通过多种方式进行导入。

Example 1, Import a python module with python interpreter: 示例1,使用python解释器导入python模块:

1.Put this in /home/el/foo/fox.py: 1.将其放在/home/el/foo/fox.py中:

def what_does_the_fox_say():
print("vixens cry")

2.Get into the python interpreter: 2.进入python解释器:

 nag@sahil:/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
 >>> 

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place: 示例2,在脚本中使用execfile或(Python 3中的exec)在适当的位置执行另一个python文件:

1.Put this in /home/el/foo2/mylib.py: 1.将其放在/home/el/foo2/mylib.py中:

def moobar():
print("hi")

2.Put this in /home/el/foo2/main.py: 2.将其放在/home/el/foo2/main.py中:

execfile("/home/el/foo2/mylib.py")
moobar()

Example 3. Use from ... import ... functionality: 例子3.使用from ... import ...功能:

1.Put this in /home/el/foo3/chekov.py: 1.将其放在/home/el/foo3/chekov.py中:

def question():
print "where are the nuclear wessels?"

2.Put this in /home/el/foo3/main.py: 2.将其放在/home/el/foo3/main.py中:

from chekov import question
question()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM