简体   繁体   中英

ModuleNotFoundError: No module named 'src' in python

I have the following folder structure:

src
 |_ __init__.py
    example.py
test
 |_ test.py
# __init__.py
class API:
    def something(self):
        print('folder src | file __init__')
# example.py
class Example:
    def doingSomething(self):
        print('folder src | file example')
# test.py
import src
from src.example import Example

class Test:
    def somethingElse(self):
        print('folder test | file test')

when I run the test.py file, I get the following error:

Traceback (most recent call last):
  File "<my path>\test\test.py", line 1, in <module>
    import src
ModuleNotFoundError: No module named 'src'

Unless you import the example module in your src/__init__.py file, you need to specify the module name (ie, example ) within the package (ie, src ).

from src.example import Example

You don't actually need to include the "src" folder in your path. For example, if you're folder structure looks like this:

  • src
    • app1

      • models1.py
      • views1.py
    • app2

      • models2.py
      • views2.py

You can import models2.py into views2.py like this:

from .models2 import ClassName

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