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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mathmaniage
  • 299
  • 1
  • 14
  • put a `__init__.py` in the folder – Arpit Solanki Aug 19 '17 at 07: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. – Jacques de Hooge Aug 19 '17 at 07:39
  • 1
    Write a `setup.py` and install it? – jonrsharpe Aug 19 '17 at 07:39
  • @JacquesdeHooge, how do I edit my PYTHONPATH? And what is this __init__.py? – mathmaniage Aug 19 '17 at 08:39

1 Answers1

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='name@mail.in',
  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

Kallz
  • 3,244
  • 1
  • 20
  • 38