Create own modules

A module is a python file that contains a set of general functions that can be used in other python scripts.

Python import module file from subdirectory

1) Create module file mytools.py containing functions (def myfunc(): ... )

2) Make project directory as Python package by adding (empty) file __init__.py

ls myproject/

mytools.py

__init__.py

3.1) add module directory to path (in .bashrc)

export PATH=$HOME/my/path/to/myproject/:$PATH

3.2) or, better, import path within python

python

import sys

sys.path.append("/home/myname/my/path/to/myproject/")

4) import own module in another python script, and run function

python

import myproject.mytools as mytools

mytools.myfunc()

https://docs.python.org/3/tutorial/modules.html

Module testing

The filename mymodule.py is the module name

Module scripts are only processed (compiled) the first time of using import, later changes are not updated by importing again.

import mytools

reload(mytools)

mytools.myfunct(..)

For editing and testing, modules can be run by itself using internal test functions 'testfunc'.

To avoid processing test functions also during import, it can be covered by a __main__ check .

if __name__ == '__main__':

testfunc()

__main__ run as imported module

>>> import mymodule

>>> mymodule.__name__

'mymodule'

run directly the module file

>>>__name__

'__main__'

add module/package directory 'python' to visible python paths

import sys

sys.path.append('/home/myname/python')

sys.path # check paths

['', '/home/myname/python', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/home/scholz/myname']

or externally add to .bashrc

export PYTHONPATH=$PYTHONPATH:~/python

https://docs.python.org/3/tutorial/modules.html