0

I got the following error when I compiled as followed. Why the errors? Thanks in advance.

cd /root/rel_path/ctlib/src 
python3 main_prog.py

Error:

root@Linux:~/rel_path/ctlib/src# python3 main_prog.py 
Traceback (most recent call last):
  File "main_prog.py", line 1, in <module>
    from ctlib.auto import CtAuto
ModuleNotFoundError: No module named 'ctlib'
root@Linux:~/rel_path/ctlib/src

Example path tree:

/root/rel_path/
             |--- ctlib
                     |--- src
                            |--- main_prog.py
                     |--- auto
                            |--- __init__.py

Code:

main_prog.py code:

from ctlib.auto import CtAuto

print("hello")

init.py code:

#!/usr/bin/env python3

class CtAuto:
    def print_hello(self):
        print("Hello, from CtAuto")

2 Answers 2

1

Your import is actually looking for the CtAuto class in auto.py which does not exist in your tree:

/root/rel_path/
             |--- ctlib
                     |--- src
                            |--- main_prog.py
                     |--- auto
                            |--- __init__.py
                     |--- auto.py

Use from ctlib.auto.auto import CtAuto instead and put your CtAuto class in /root/rel_path/ctlib/auto/auto.py

[EDIT]
Because you __main__ is in a subdirecory you need to add the rootdir of the project to the Pythonpath. (before importing CtAuto)

import sys
sys.path.append('../../')

or

import sys
sys.path.append('/root/rel_path/')
Sign up to request clarification or add additional context in comments.

3 Comments

Still didn't work. Errors: root@Linux:~/rel_path/ctlib/src# python3 main_prog.py Traceback (most recent call last): File "main_prog.py", line 2, in <module> from ctlib.auto.auto import CtAuto ModuleNotFoundError: No module named 'ctlib' root@Linux:~/rel_path/ctlib/src#
Sorry, I missread your question. Updated my Post. Now it is working for me locally.
Yes, it worked for me too. Found temporary change to PYTHONPATH environment variable is OK too: export PYTHONPATH="${PYTHONPATH}:/root/rel_path/"
1

Since you are running the program in sub-level (child) and doing import at the same level without creating any packages, which is a relative import on the same level.

Changing the main_prog.py like below will make it work.

import sys
sys.path.append("..")
from auto import CtAuto

print("hello")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.