Python ModuleNotFoundError despite __init.py__ and correct PYTHONPATH on Linux

Question:

I’m trying to get a Python script running on my Ubuntu server. I have the following directory structure:

/home/pythontest
      |_  __init__.py
      |_  main.py
      |_  module_a.py

inside module_a.py:

def print_a():
    print('a')

inside main.py:

from pythontest.module_a import print_a
def execute():
    print_a()
execute()

When I run main.py in PyCharm on my Windows machine, it prints a as expected, on my Linux machine, when I call python3 main.py I get a

Traceback (most recent call last):
    File "main.py", line 1, in <module>
        from pythontest.module_a import print_a
ModuleNotFoundError: No module named 'pythontest'

The __init__.py exists (and is completely empty) and I have added the directory /home/pythontest to the PYTHONPATH with the following command:

export PYTHONPATH="${PYTHONPATH}:/home/pythontest"

(testing this with echo $PYTHONPATHalso yields the correct path)

Additional Notes:
– The python3 version on my machine is Python 3.6.9
– My Server runs Ubuntu 18.04
– All those files are written in PyCharm on Windows and copied over via SSH

Asked By: Jonas Reinhardt

||

Answers:

You’re importing pythontest(.module_a), which is located in /home. That’s what you’re supposed to add to PYTHONPATH:

export PYTHONPATH=${PYTHONPATH}:/home

More details on [Python.Docs]: The import system.

Or you could not reference the package name from within it (consider relative imports):

from .module_a import print_a

Might also want to check [SO]: How PyCharm imports differently than system command prompt (Windows) (@CristiFati’s answer), to see why does it work from PyCharm.

Answered By: CristiFati

You need to change your import in main.py to:

from module_a import print_a

since module_a is a module that exists in the path that you exported.

Answered By: Tomasz Bartkowiak
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.