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

Python 为什么我不能同时从模块目录内部和外部导入模块?,python,Python,我当前的项目具有以下结构: src: file1.py file2.py file2中有一些函数我想导入到file1中并使用。因此,文件1具有以下行: from file2 import func1, func2 在src目录中运行终端并键入: from file1 import * 一切正常。但是,当跳出src目录并在python终端中键入 from src.file1 import * 我得到以下错误: Traceback (most recent call la

我当前的项目具有以下结构:

src:
   file1.py
   file2.py
file2中有一些函数我想导入到file1中并使用。因此,文件1具有以下行:

from file2 import func1, func2
在src目录中运行终端并键入:

from file1 import *
一切正常。但是,当跳出src目录并在python终端中键入

from src.file1 import *
我得到以下错误:

    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'
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
然后,它在src文件夹外部运行良好。但在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 
ModuleNotFoundError: No module named 'file2'
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

是否仍有办法解决此问题?

在文件1中,在从文件2导入函数之前,可以指定文件2的目录:

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

from file2 import func1, func2
这将使它在src目录之外运行时更加健壮。

明白了

file1.py:

from file2 import func1, func2
func1()
func2()
file2.py具有以下功能:

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

def func2():
    print('yeeeah func2')
src: __初始值 file1.py file2.py

来自src:

src$ python file1.py 
印刷品:

yeeeeah func1
yeeeah func2
从其他地方:

src$ cd ..
test_stack$ python src/file1.py 
印刷品:

yeeeeah func1
yeeeah func2

假设src是setup.py requirements.txt等活动的主目录

您要花一整天的时间来理解python导入,longstory short file1可能看不到file2,当在src中运行时,pythonpath可以看到它,在src中放一个_init_uuuy.py文件,然后使用from.file2导入重试……我会尝试@E.Serra所说的。。。每次我想我理解python导入时,我都会陷入一种令我吃惊的境地。另一种选择是只将src添加到您的路径简言之,您必须决定src是否是一个包。也就是说,file2.py是应该称为src.file2还是仅仅称为file2。同时做这两件事不是个好主意。这能回答你的问题吗?哦,是的,当我写问题的时候,我有点明白了。我只是想知道是否有某种方法可以使用该文件。不要这样做,这是一种不好的做法,学习如何使用适当的导入这可能会复制src中的任何模块,这可能会导致各种不明显的错误,例如两个版本之间的isinstance故障。是的,这对我来说也很好。但是,如果您尝试在其他地方运行python终端,比如说在包含src文件夹的目录中,它将抛出一个错误…不,这可以从src和外部运行,只要您拥有init.pyfile@E.Serra您的python是否指向python 2?Python3删除了隐式相对导入。我使用的是Python3,init.py文件表明该目录可以用作模块