How to fix “no module named ‘app_one'”

I have a Python package with the following structure.

>python_package       # package root directory
    >app_one          # subpackage directory
        >__init__.py
        >views.py
   
    >app_two          # another subpackage directory
        >__init__.py
        >views.py

Code for app_one/views.py:

def show(): 
    print('do something')

Codes for app_two/views.py:

from app_one.views import show
show()

The problem is, whenever I try to run views.py of app_two from the terminal, I get an error

No module named ‘app_one’

But when I open the package python_package in the PyCharm IDE, I’m getting no issue, everything works perfectly.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This error occurs because, the path to the file app_one is not in the current path, and you have to add it to the path using sys.path.append Try :

import sys
sys.path.append('./app_one')
from views import show
show()

Method 2

I have created the same directory structure as you had and gave it a try and it is working.

I think what you were missing is that adding this line before you import in app_two/views.py:

sys.path.insert(0, os.path.abspath(__file__ + "../../../"))

Please have a look at the attached image which has detailed information

How to fix "no module named 'app_one'"


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x