简体   繁体   English

Python - 同一目录中的模块的“ImportError:无法导入名称”

[英]Python - "ImportError: cannot import name" for modules in the same directory

I have two python files in the same directory.我在同一个目录中有两个 python 文件。 I have also __init__.py file as well.我也有__init__.py文件。 Python version is: 3.9.7 Python版本为: 3.9.7

Can't figure out why I can't import the modules.无法弄清楚为什么我不能导入模块。

a.py

def aaa():
    print ("test")

b.py

from a import aaa

aaa()

Error:错误:

from a import aaa
ImportError: cannot import name 'aaa' from 'a' (/usr/lib64/python3.9/a.py)

Also it doesn't work:它也不起作用:

from .a import aaa

ImportError: attempted relative import with no known parent package

Running it as: python b.py I have tried other options but without success.将其运行为: python b.py我尝试了其他选项但没有成功。

Update: The same simple code from a import aaa aaa() without init.py works on python 2.7.更新:没有 init.py from a import aaa aaa()的相同简单代码适用于 python 2.7。

OS: 
"Red Hat Enterprise Linux 8.5"

Thanks!谢谢!

对于同一文件夹中的相对导入,请使用单个.

from .a import aaa

Like Samathingamajig pointed out, you need relative imports.就像 Samathingamajig 指出的那样,您需要相对进口。

So, first, change the line in b.py to:因此,首先,将b.py中的行更改为:

from .a import aaa

You also need to deal with the fact that you now have a package instead of a single module.您还需要处理您现在拥有一个包而不是单个模块的事实。 And Python needs to know how to find your modules. Python 需要知道如何找到你的模块。

One way tot deal with that, is to run it using -m .解决这个问题的一种方法是使用-m运行它。 If your Python files are in /some/dir/myproject/ , run it as follows:如果您的 Python 文件位于/some/dir/myproject/中,请按如下方式运行它:

cd /some/dir
python3 -m myproject.b

Note the namespace dot replacing the directory separator in that last command.请注意名称空间点替换了最后一个命令中的目录分隔符。

Alternatively, install your package (I recommend learning about packaging but for now you can simply move the myproject directory into one of the directories in sys.path ), and then you could have any Python file import myproject.b or run python3 -m myproject.b from any directory.或者,安装你的包(我建议学习打包,但现在你可以简单地将myproject目录移动到sys.path中的目录之一),然后你可以让任何 Python 文件import myproject.b或运行python3 -m myproject.b从任何目录。

If you want to have a package that can be used both as a library and a stand-alone application, you could add a __main__.py file with the code to run it as an application.如果您想拥有一个既可用作库又可用作独立应用程序的包,您可以添加包含代码的__main__.py文件以将其作为应用程序运行。 That way python3 -m myproject would run your main project这样python3 -m myproject将运行您的主项目

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

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