简体   繁体   English

为什么我不能从模块目录内部和外部导入模块?

[英]Why can't I import a module from both inside the module directory and outside it?

My current project has the following structure:我当前的项目具有以下结构:

src:
   file1.py
   file2.py

There are some functions in file2 which I would like to import into file1 and use. file2 中有一些函数我想导入到 file1 中并使用。 So the file 1 has the following lines:所以文件 1 有以下几行:

from file2 import func1, func2

When run the terminal in the src directory and type:在 src 目录中运行终端并键入:

from file1 import *

everything works well.一切正常。 However, when go outside the directory src, and type in the python terminal但是,当 go 在目录 src 之外时,在 python 终端中键入

from src.file1 import *

I get the following error:我收到以下错误:

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/bhavincvts/Desktop/greenleap/solarAFD1/src/file1.py", line 3, in <module>
    from file2 import func1, func2 
ModuleNotFoundError: No module named 'file2'

After that, I tried changing the import statement to,之后,我尝试将导入语句更改为,

from .file2 import func1, func2

it then works well from outside the src folder.然后它在 src 文件夹之外运行良好。 But when running the terminal inside the src folder, it shows the following error:但是在 src 文件夹中运行终端时,它显示以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/bhavincvts/Desktop/greenleap/solarAFD1/src/file1.py", line 3, in <module>
    from .file2 import func1, func2 
ImportError: attempted relative import with no known parent package

Is there anyway to fix this?有没有什么办法解决这一问题?

got it;知道了;

file1.py:文件 1.py:

from file2 import func1, func2
func1()
func2()

file2.py has the functions: file2.py 具有以下功能:

def func1():
    print('yeeeeah func1')

def func2():
    print('yeeeah func2')

src: __init__.py file1.py file2.py源代码:__init__.py file1.py file2.py

from src:来自源代码:

src$ python file1.py 

Prints:印刷:

yeeeeah func1
yeeeah func2

from somewhere else:从其他地方:

src$ cd ..
test_stack$ python src/file1.py 

Prints:印刷:

yeeeeah func1
yeeeah func2

Assuming src is your main directory (where setup.py requirements.txt etc live)假设 src 是您的主目录(setup.py requirements.txt 等所在的位置)

In file1, before you import the functions from file2, you can specify the directory of file2:在 file1 中,在从 file2 导入函数之前,可以指定 file2 的目录:

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

from file2 import func1, func2

This should make it more robust against running outside the src directory.这应该使它更健壮地防止在 src 目录之外运行。

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

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