Python ModuleNotFoundError only in command line execution not in IDE

72 Views Asked by At

I see a ModuleNotFoundError error when running a simple program.

The project is created using Poetry, and the setup is as shown in the screenshot.

enter image description here

h.py has this:

def add(num1, num2):
    return num1 + num2

s.py has this:

from src.helper.h import add


def main():
    print(add(1, 2))


if __name__ == "__main__":
    main()

If I execute the code from within PyCharm IDE, I see the output correctly. If I execute from command line using python3 src/scripts/s.py, I see an error as below:

Traceback (most recent call last):
  File "/Users/me/dev/python-learn/src/scripts/s.py", line 1, in <module>
    from src.helper.h import add
ModuleNotFoundError: No module named 'src'

I tried adding __init.py__ to each of the directories src, helpers, and scripts. That did not resolve the issue.

Can someone tell me what I am missing?

2

There are 2 best solutions below

0
techjourneyman On BEST ANSWER

I was able to resolve it by adding the following in the pyproject.toml file

[tool.poetry.scripts]
script1 = "src.scripts.script1:main"

and running it as

poetry run script1
0
John Vandivier On

try poetry run python3 [your_script].py

although poetry has initialized your project and you may have run poetry install, you are not necessarily utilizing the poetry environment when you directly run python3 src/scripts/s.py

there are two main ways to access the poetry environment:

  1. inline, as i mention above
  2. by activating a persistent poetry shell. see more info here in the poetry docs