Packages‎ > ‎

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 containing useful functions (def myfunc(): ... )

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

ls myproject/

3) add module directory to path (in .bashrc)
export PATH=$HOME/my/path/to/myproject/:$PATH

4) import own module in another python script, and run function
import myproject.mytools as mytools

Module testing

The filename 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

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__':

__main__ run as imported module
>>> import mymodule
>>> mymodule.__name__

run directly the module file


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

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