Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot import a module after os.chdir() [duplicate]

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.

like image 233
Omid Avatar asked Dec 18 '22 23:12

Omid


1 Answers

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')
like image 91
Daniel Avatar answered Feb 17 '23 05:02

Daniel