1

I have a custom Python package (my_package) located in a directory (super_dir). I have a script (my_script.py) in a nested directory of super_dir (let's call it sub_dir) that imports my_package and uses it.

I receive a ModuleNotFound error if I run the script from a terminal window (where my working directory is super_dir) by calling python sub_dir/my_script.py. It does work, however, if my_script.py is located within super_dir, rather than within sub_dir and I simply call python my_script.py. It also works if I run my_script.py in VSCode in the Python Interactive window (even if I'm my working directory is sub_dir) as long as I have the lines

import os
os.chdir('....further_paths/super_dir/') 

at the top of the script.

My question is: how can I get the script to run from the terminal such that it can remain within sub_dir but will still be able to import my_package, even though my_package is located 'up' a whole directory?

Even if the lines^ above (that change the current directory) are included at the top of the script, I still get the ModuleNotFound error as long as I run the script from a terminal window and my_script.py is not located in super_dir.

Thank you in advance, I hope my question was clear!

2
  • So you have the layout of super_dir/my_package.py and super_dir/sub_dir/my_script.py? Commented Apr 9, 2020 at 21:37
  • Yes exactly -- except that it's really super_dir/my_package/init.py and super_dir/my_package/my_functions.py since there are modules and .py files within the overarching my_package Commented Apr 10, 2020 at 10:46

2 Answers 2

3

You have two options. One is you need to set PYTHONPATH to super_dir so that when Python executes your script it looks there for packages during import.

The other option is to make my_script a module and you use python -m sub_dir.my_script to execute the code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the clarification! Much appreciated
0

As long as the script.py you would like to import is not in a parent directory one solution is to make sure (or set) the current working directory for importing script in child directorys to work: import child-dir.script or from child-dir import script.

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.