Jacob Pavlock
Jacob Pavlock

Reputation: 751

Python how to import local module?

I have the following directory structure in Ubuntu. I'm trying to import the module config from my local package my_app into my script my_app_script.py

$ tree
.
├── my_app/
│   ├── config.py
│   ├── __init__.py
│   └── test/
├── my_app-info # created by pip install -e .
│   ├── dependency_links.txt
│   ├── PKG-INFO
│   ├── requires.txt
│   ├── SOURCES.txt
│   └── top_level.txt
├── bin/
│   └── my_app_script.py
├── LICENSE
├── README.md
└── setup.py
# setup.py
setup(
    name='my_app',
    version='0.1.2',
    description='',
    url='',
    packages=['my_app'],
    scripts=['bin/my_app_script.py'],
    install_requires=[],
    python_requires='>=3.6',
    )
# my_app_script.py
from my_app import config

When I run my_app_script.py it results in "ImportError: cannot import name 'config'

What am I doing wrong?

Edit: I am trying to follow this guide on packaging a program.

Upvotes: 1

Views: 3088

Answers (2)

Abhishek Agarwal
Abhishek Agarwal

Reputation: 724

You can use either of below approaches.

The first approach seems best to me as the script will always set the path relative to it, and will also work if you clone your repos.

  1. Add an __init__.py in parent directory(Next to setup.py).

And add below line in my_app_script.py

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, "my_app")))

What this will do is add .../my_app to PYTHONPATH at runtime, when my_app_script.py is executed.

  1. Add an env.sh in parent directory. Below should be the contents of env.sh.

    export PYTHONPATH=$(pwd):$PYTHONPATH

Now cd int the directory where env.sh is kept and then source it

source env.sh

Now run your my_app_script.py

python bin/my_app_script.py
  1. Set PYTHONPATH from commandline.

    PYTHONPATH=$(pwd) python bin/my_app_script.py

Upvotes: 0

ramez
ramez

Reputation: 431

You need an __init__.py file in the parent directory as well as in bin directory.

Upvotes: 1

Related Questions