107

Here's my Python folder structure

-project
----src
------model
--------order.py
------hello-world.py

Under src I have a folder named model which has a Python file called order.py which contents follow:

class SellOrder(object):
    def __init__(self,genericName,brandName):
        self.genericName = genericName
        self.brandName = brandName

Next my hello-world.py is inside the src folder, one level above order.py:

import model.order.SellOrder

order = SellOrder("Test","Test")

print order.brandName

Whenever I run python hello-world.py it results in the error

Traceback (most recent call last):
  File "hello-world.py", line 1, in <module>
    import model.order.SellOrder
ImportError: No module named model.order.SellOrder

Is there anything I missed?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
user962206
  • 15,637
  • 61
  • 177
  • 270
  • what should be the contents if __init__.py? – user962206 May 15 '16 at 00:12
  • https://docs.python.org/2/tutorial/modules.html#packages – Padraic Cunningham May 15 '16 at 00:16
  • 2
    `__init__.py` can be empty or can contain code. it is common for projects to expose their primary / public classes at the package level. In your case you could add `from model.order import SellOrder` so that other code can do `from project import Sellorder` instead of `from project.model.order import SellOrder`. – miraculixx May 15 '16 at 03:46

15 Answers15

74

All modules in Python have to have a certain directory structure. You can find details here.

Create an empty file called __init__.py under the model directory, such that your directory structure would look something like that:

.
└── project
    └── src
        ├── hello-world.py
        └── model
            ├── __init__.py
            └── order.py

Also in your hello-world.py file change the import statement to the following:

from model.order import SellOrder

That should fix it

P.S.: If you are placing your model directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path.

RafazZ
  • 4,049
  • 2
  • 20
  • 39
  • 16
    also it's considered good practice not to have a `src` directory. that makes sense too because if you import your code somewhere else you should be able to `import project.model` and not `project.src.model`. – miraculixx May 15 '16 at 00:57
  • Very late to this thread, but I have the exact same structure as above, and using the solution above, I still can only run my program (`locust -f src\main.py ...`) if I use `from src.module.submodule import main`. Even with __init__.py in place. Maybe my `cwd` should be inside `src`? – Guy Feb 08 '22 at 08:30
  • 2
    this doesn't seem to be working. I have `__init__.py` in every folder but it still cannot be imported. Pycharm didn't show up with any errors, but the terminal kept showing up errors. – Dekriel May 03 '22 at 13:05
  • For some reason it works when I run the python file. But when executing the same commands in the interactive mode, it does not work. Very intriguing. – Eduardo Reis May 11 '22 at 15:58
  • Yeah, adding `__init__.py` doesn't fix this issue for me. Even in the same directory (i.e. both scripts are under the same folder) – wesmlr Jul 13 '23 at 18:53
  • @Dekriel @wesmir If the project is setup as described in the [Modules](https://docs.python.org/3/tutorial/modules.html#packages), it should work. However, there are many reasons why your particular case does not. Easy things to try: (1) Check your `PYTHONPATH`; (2) Check that your package is in the `sys.path`; (3) Make sure you are importing correctly (path is proper); (4) Make sure your package name does not clash with an existing/installed package... Without an actual error, there is very little I can infer what might be going on. – RafazZ Jul 22 '23 at 03:36
21

If it's your root module just add it to PYTHONPATH (PyCharm usually does that)

export PYTHONPATH=$PYTHONPATH:<root module path>

for Docker:

ENV PYTHONPATH="${PYTHONPATH}:<root module path in container>"
Sergey Luchko
  • 2,996
  • 3
  • 31
  • 51
  • 2
    If you're going to be running this code from your root module, it is very convenient to have the current directory, `.`, in your PYTHONPATH, if it's not there already. Linux: `export PYTHONPATH=$PYTHONPATH:.`. Windows: `set PYTHONPATH=%PYTHONPATH%;.` – Akaisteph7 Jul 05 '22 at 15:56
  • Thank you very much!! I was calling different scripts on my project depending on the parameter passed to `docker-compose up`, and this was the only way the imports started to solve correctly on docker compose and not only when running it via Python directly. – LucianoBAF Sep 21 '22 at 22:08
10

you need a file named __init__.py (two underscores on each side) in every folder in the hierarchy, so one in src/ and one in model/. This is what python looks for to know that it should access a particular folder. The files are meant to contain initialization instructions but even if you create them empty this will solve it.

4

It's easier if you use this code

python3 -m module.sub_module

For example:

python3 -m entrypoint.settings
MD Mushfirat Mohaimin
  • 1,966
  • 3
  • 10
  • 22
2

Just add your project root directory to environment variable: PYTHONPATH. so for the below project structure, just add Rootdir path(For e.g: add E:\Projects\Rootdir) in PYTHONPATH.

Rootdir
└── pkg2
    ├── b.py
    ├── c.py
     └── pkg2
      ├── b.py
      ├── c.py
    
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Bharti Jha
  • 141
  • 1
  • 5
1

After trying to add the path using:

pip show

on command prompt and using

sys.path.insert(0, "/home/myname/pythonfiles")

and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.

I simply copied the module that wasn't found from the path "Mine was in

C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages 

so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
1

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

lpkej
  • 445
  • 6
  • 23
  • 2
    That's why you should never use `#!/usr/bin/python` but `#!/usr/bin/env python` (or `#!/usr/bin/env python3` for Python3, or possibly `#!/usr/bin/env python3.8` for a specific version). This will also work when using virtual environments, while the first form won't. – wovano Aug 22 '20 at 10:02
1

I only use Python as a secondary language and probably made a newbie-error. I had similar problem and my error was calling:

import requests

I got the error

ModuleNotFoundError: No module named 'requests.adapters'; 'requests' is not a package

Turns out the file I created in the same folder named "requests.py" made a conflict. Renaming the file made it work again.

Titken
  • 81
  • 4
0

You need to make sure the module is installed for all versions of python

You can check to see if a module is installed for python by running:

pip uninstall moduleName

If it is installed, it will ask you if you want to delete it or not. My issue was that it was installed for python, but not for python3. To check to see if a module is installed for python3, run:

python3 -m pip uninstall moduleName

After doing this, if you find that a module is not installed for one or both versions, use these two commands to install the module.

  • pip install moduleName
  • python3 -m pip install moduleName
Walker Sutton
  • 380
  • 1
  • 4
  • 7
  • 21
    This is not what the question is asking – Roy May 21 '19 at 10:40
  • 4
    Well, this helped me. Those modules were working through PyCharm but when I ran my program through Terminal it showed `ModuleNotFoundError` and this solution fixed my problem. – Verma Aman Jul 16 '19 at 12:56
0

If you are using VSCode, what worked for me was I changed the interpreter of my IDE, here is a quick snapshot: enter image description here

I install my packages through pip3, it appears to be like my Homebrew handles all of the packages I installed previously, so that's the tweak I had to make!!

0

Another solution depends on where you are running this code from.

If you try running python hello-world.py (from the src directory), you would have to do the following two things for this to work:

  1. Change the import line in hello-world.py to from model.order import SellOrder
  2. If not already there, add to your system environment variable. Key PYTHONPATH, value .
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
0

I have write on Powershell $env:PYTHONPATH = "C:\Users\adolfo\Desktop\borrar" with the route of the root folder of the project

  • I'm voting to delete this answer. Because this is the same as this [answer](https://stackoverflow.com/a/65164141/7758804), which already states to update `PYTHONPATH`, I can only assume it was posted as a "thank you" or "confirmation". Please don't add "thank you", or "confirmation" answers. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation), you will be able to [vote up questions and answers](https://stackoverflow.com/help/privileges/vote-up) that you found helpful. [From Review](https://stackoverflow.com/review/late-answers/34247909) – Trenton McKinney Apr 25 '23 at 22:39
  • Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful. - [From Review](/review/late-answers/34247909) – Trenton McKinney Apr 25 '23 at 22:39
-1

if you are using python 3 then try the below command. I was facing similar issue , this fixed my problem

pip3 install

Anushree Garg
  • 162
  • 1
  • 4
-1

I solved it by deleting previous python2 and only using python3 which is working fine on windows 10

General Grievance
  • 4,555
  • 31
  • 31
  • 45
-6

you need to import the function so the program know what that is here is example:

import os 
import pyttsx3

i had the same problem first then i import the function and it work so i would really recommend to try it