ModuleNotFoundError: No module named 'ProductionAPI'

I’m relatively new to python. I cloned a repo called ‘Python’ from git. It has a script called AllScan.py within a folder(Name:SampleScripts). I have another file called ProductionAPI.py which is not located in any folder and is directly in this “Python” repo. This AllScan.py script calls one of the function in ProductionAPI.py(I have imported like this “from ProductionAPI import ProductionAPI”). This repo “Python” has multiple folders in it. Now, the problem is when I try to run my script AllScan.py from command line using a cmd like (py SampleScripts/AllScan.py) it throws a ModuleNotFoundError. It works fine in pycharm though. Can anybody please help me resolve this issue ?

Actual Error:
D:Python>py SampleScripts/AllScan.py
Traceback (most recent call last):
File “D:\Python\SampleScripts\AllScan.py”, line 8, in
from ProductionAPI import ProductionAPI
ModuleNotFoundError: No module named ‘ProductionAPI’


My project structure

I’m relatively new to python. I cloned a repo called ‘Python’ from git.
It has a script called AllScan.py within a folder(Name:SampleScripts).
I have another file called ProductionAPI.py which is not located in any
folder and is directly in this “Python” repo. This AllScan.py script
calls one of the function in ProductionAPI.py(I have imported like this
“from ProductionAPI import ProductionAPI”). This repo “Python” has
multiple folders in it. Now, the problem is when I try to run my script
AllScan.py from command line using a cmd like (py
SampleScripts/AllScan.py) it throws a ModuleNotFoundError.

Python finds modules by searching in folders named in the PYTHONPATH
environment variable, and then in the standard places for the Python
interpreter itself (the venv lib if you have one, the stdlib it shipped
with).

When you run a script on the command line, the folder of the script is
prepended to the search path, letting the script import files in the
same folder as the script.

If you want to use more .py files, their folder needs to be in the
PYTHONPATH. The URL below suggests that on Windows you can modify it
like this:

 set PYTHONPATH=%PYTHONPATH%;D:\Python

as described here:

I would prepend your top level folder rather than appending it.

Likely your PYTHONPATH is empty or unset anyway, so you could just go:

 set PYTHONPATH=D:\Python

Try that and see if the behaviour improves.

You can inspect what path Python ends up searching from inside your test
script like this:

 import sys
 print(sys.path)

That will let you see everything, and whether your modifications to
PYTHONPATH are having the desired effect.

It works fine in pycharm though.

PyCharm is likely making these arrangements for you.

The links and discussion in this thread may be helpful:

1 Like