Saturday, June 25, 2016

How to package a Python module

Python is an interesting coding language. It can be used to implement the solution for some simple tasks in very short time. There are many useful modules out there you can use for your task. Below is a simple way to package your Python application as a module. Then you can distribute it and it can be used by others.

It is recommended to organize your Python application in the following project structure

my-project
    ---mypackge
        ---__init__.py
        ---__main__.py
        ---package-data
            ---package.conf
            ---package.txt
        ---mainscript.py
    ---mypackge-runner.py
    ---setup.py


Below is a very simple example of the setup.py script. More details about the setup script are here.

setup.py:
from setuptools import setup, find_packages

setup(
    name='my-project',
    packages=find_packages(),
    description='my python project',
    entry_points={
        "console_scripts": ['mypackage = mypackage.mainscript:main']
    },
    version='1.0.0',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Programming Language :: Python :: 3'],
    install_requires=[
        'requests'
    ],
    package_data={
        'mypackage': ['package-data/package.conf',
                        'package-data/*.txt']
    },
    author='Andrew Liu')




Some important values are explained as below.

1. entry_points

   This is the entry point of your code. "console_scripts" defines which function to execute when your application is called from command line. In the example, it is the main() function in mypackage.mainscript.py.

2. install_requires
   This is to define all the dependencies of your module.
3. package_data
   All other files which are not python file you want to package into your module need to be listed here.

To install your python module
cd path-to-my-project
python setup.py install

To run the package in your project
python -m mypackage
To run the wrapper script
python mypackage-runner.py
To check install 
command -V mypackage
To run as module
mypackage