4

I have a python file with the class A defined in it in a different directory than the one I am working in. I want to import a module from that class in my script. I wrote something like this in jupyter:

import os
parent_dir = 'path/to/class'
os.chdir(parent_dir) 
from A import a

It works perfectly fine and I get to execute the program. However when I run the script in the same directory from the terminal, I get this error:

ModuleNotFoundError: No module named 'a'

I put a os.getcwd() before the error to make sure it is in the same directory, and when I go to that directory from the terminal and import the module directly there are no errors. I wonder why I get this error when running the script.

Omid
  • 2,617
  • 4
  • 28
  • 43

2 Answers2

16

Don't use os.chdir, because it changes a global state, that can lead to unexpected behaviour somewhere else.

Expand sys.path:

import sys
sys.path.append('/absolute/path/to/module')
Daniel
  • 42,087
  • 4
  • 55
  • 81
-1

You can use from path.to.class import className