简体   繁体   中英

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

I have two python files in the same directory. I have also __init__.py file as well. Python version is: 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.

Update: The same simple code from a import aaa aaa() without init.py works on python 2.7.

OS: 
"Red Hat Enterprise Linux 8.5"

Thanks!

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

from .a import aaa

Like Samathingamajig pointed out, you need relative imports.

So, first, change the line in b.py to:

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.

One way tot deal with that, is to run it using -m . If your Python files are in /some/dir/myproject/ , run it as follows:

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.

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. That way python3 -m myproject would run your main project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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