5

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.

0

2 Answers 2

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

it's better to do sys.path.append(os.path.join(os.path.dirname(__file__),'path/to/module')
@Jean-FrançoisFabre: I did have this version, but not sure, if the OP uses paths relative to the script file.
-2

You can use from path.to.class import className

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.