简体   繁体   中英

How to import a module into another module

This is the structure of my project:

project (folder)
   main.py
   assets (folder)
      a.py
      b.py

When I import module a into module b and run main.py, I get No module named 'a' .

Yet if I run b.py directly, it imports a.py just fine.

a and b are in the same directory, so what am I missing? FWIW, I am using Python 3.10.

main.py:

import assets.b as bb

a.py:

def func(x):
    print(x)

b.py:

import a
a.func('hello')

Update your b.py as follows

from . import a 
a.func('hello')

or

from assets import a
a.func('hello')

In first case, we are telling interpreter to check in the same location as file. In second case, we are just using a fullpath. Tested with python 3.10.1 and 3.6

If you are using a folder structure, it is always best to fix you execution path and relative path according to your main.py . Implies running python3.10 b.py from assets is not acceptable.


In case, you want the functionality to do python3.10 b.py from assets folder and also python3.10 main.py then update the code as follows.

try:
  from . import a
except:
  import a

a.func('hello')

If you are sticking to a IDE like PyCharm then such errors are easy to spot and fix.

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