How Do You Write Your Own Custom, Importable Module in Python?

Problem scenario
You want to build your own Python module.  You want this module to be able to be imported on your Linux server with Python (e.g., with "import contint").  How do you write such a module?

Possible Solution #1
Write a .py file for the module, and place it where Python will look.  To find the location run these three commands:


import sys


# This command above will display directory paths for your .py file (the module that will be able to be imported).
# Ignore the .egg files that may be displayed.  (The directory paths will work if they appear without the .egg file.)
# No services need to be stopped or restarted after the file is placed in one of the above locations.   

When you use the "import" command, do NOT include the ".py" extension of the file name.  Use the file name without the ".py" file.

For example, if your module is called, and you placed it in /usr/lib/python3.7/lib-dynload/, you would run this from a >>> prompt:

import contint

If you want to use a directory location outside of what you found with the >>>  print sys.path command, see this StackOverflow posting.

Possible Solution #2
See this posting.

Leave a comment

Your email address will not be published. Required fields are marked *