Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python 3, is it possible to import a file from a subdirectory?

I have some scripts that used shared code in a different directory (that happens to be a subdirectory).

For various reasons, I do not want to package the shared code up into a Python package, nor do I want to dump all the files into a single directory, nor do I want to add the subdirectory to the path.

Is there any way to do a relative import & pull in the files in the subdirectory in Python 3?

In IPython3

import subdir.my_shared_library

works fine.

However, this fails in Python3, along with every attempt I've made to add __init__.py files and do relative imports explicitly like import .subdir.my_shared_library.

Is there a way to get around this?

like image 968
Ben Hamner Avatar asked Nov 17 '25 18:11

Ben Hamner


2 Answers

You should only need to add an __init__.py to \subdir and then import via from subdir import my_shared_library. If you don't want to compile it into a package with the rest of your code, you could also append it to your PATH using sys.path.append('subdir') or the typical export to PYTHONPATH. If you don't want to touch paths, you can just drop it in the global site-packages, or, alternatively, create a virtual environment through something like pyvenv and put your library in the package folder there.

like image 59
henrymei Avatar answered Nov 20 '25 08:11

henrymei


Try appending to PYTHONPATH from the shell like

export PYTHONPATH=$PYTHONPATH:subdir; python your_program.py

https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

But the better way to do it is to append to sys.path:

sys.path.append('subdir')
like image 37
rohithvsm Avatar answered Nov 20 '25 06:11

rohithvsm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!