dang
dang

Reputation: 2412

Python3 - ImportError: No module named

I have 2 folders:

my_python
     code.py

MyCode
     TestEntry.py

When I run the following commands:

cd /data/my_python
python3 code.py

The above works.

However, if I in my home folder and then run this:

python3 /data/my_python/code.py

I get the following error:

Traceback (most recent call last):
  File "/data/my_python/code.py", line 4, in <module>
    from TestEntry import TestEntry
ImportError: No module named 'TestEntry'

Here is the code:

import sys
import os
sys.path.append(os.path.abspath('../MyCode'))
from TestEntry import TestEntry
TestEntry().start(507,"My Param1","/param2",'.xyz',509)

Can you help me how to fix this?

Upvotes: 1

Views: 210

Answers (2)

xilpex
xilpex

Reputation: 3237

That happens because, as @mkrieger1 mentioned, your sys.path gets messed up. I have a previous answer here which explains how to set it. By sys.path getting messed up, I mean that python will look in the dir that you are running from, not the dir that the script you are running is in. Here is the recommended method:

import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'MyCode')))
... (your code)

or

import sys, os
sys.path.append(os.path.abspath(os.path.join(__file__, '..', 'MyCode')))
... (your code)

This way python will look in the dir of the file you are running as well.

Upvotes: 0

&#214;zer
&#214;zer

Reputation: 2106

You are adding a relative path to sys with your line sys.path.append(os.path.abspath('../MyCode')). Instead, you need to import relative to that file you are calling. Try this:

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from TestEntry import TestEntry
TestEntry().start(507, "My Param1", "/param2", '.xyz', 509)

Upvotes: 1

Related Questions