0

Suppose I have a directory with custom .py files. The directory is called useful_scripts and a subdirectory called tested_scripts which also contains scripts (.py files).

I've seen on some articles, import statements like:

from useful_scripts.tested_scripts import sth 

How could we install our custom directory modules in such a convienient way so that we could access it like above?

4
  • put a __init__.py in the folder Commented Aug 19, 2017 at 7:23
  • Make a dir useful_scripts with a subdir tested_scrips where you put your script sth.py. Add useful_scripts to your PYTHONPATH and put an (empty) __init__.py in both useful_scripts and useful_scripts/tested_scripts. If you'd rather not add anything to your PYTHONPATH you can also add useful_scripts to sys.path programmatically. Commented Aug 19, 2017 at 7:39
  • 1
    Write a setup.py and install it? Commented Aug 19, 2017 at 7:39
  • @JacquesdeHooge, how do I edit my PYTHONPATH? And what is this init.py? Commented Aug 19, 2017 at 8:39

1 Answer 1

1

If you have multiple modules (Python file with .py ) in directory and want to import one module in another module then first define that directory to a python directory or package

Packages are namespaces which contain multiple packages and modules.Each package in Python is a directory which MUST contain a special file called __init__.py

Python Package

Your directory structure should be like this if you want to import modules or package

enter image description here

Now you can import module a.py in module b.py or module b.py in module a.py

If you want to install custom lib then create setup.py the file where coustomlib directory exists ( create setup.py outside the coustomlib directory or along coustomlib )

in setup.py

#!/usr/bin/env python from distutils.core import setup from setuptools import setup, find_packages setup(name='coustomlib', version='1.0', description='Python coustom lib ', author='your name', author_email='[email protected]', packages=find_packages(), ) 

for install run

python setup.py install 

After install coustomlib you can import it any module

import coustomlib 

Or

from coustomlib.module1 import a 

More info about setup.py

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

2 Comments

@Kaliz, why can the init.py be empty?
@BeshalJaenal its already answer here 'stackoverflow.com/questions/448271/what-is-init-py-for'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.