Scratchpad

Pierre Palatin random posts.

Python project from scratch with distutils and friends

Posted at — Jan 1, 2006

Python has several more or less standard tools to properly create and/or distribute python code. This shows a practical starting point.

A few tools exists:

We’re going to use Distribute and PIP here it looks like they become the standard.

Distribute guide has more complete and accurate documentation. What I’m describing below is really the minimal set to get started with a basic python project.

Let’s assume that your project is called $PROJECT. We’ll store it in $BASEDIR, typically something like hello-0.1. $BASEDIR is the current directory.

 wget 'http://bitbucket.org/ianb/virtualenv/raw/tip/virtualenv.py'
 mkdir -p env/include/multiarch-x86_64-linux ln -s ../python2.6 \   env/include/multiarch-x86_64-linux/python2.6
 python virtualenv.py --no-site-packages --distribute env

It will create a subdirectory env containing the virtual environment.

 source env/bin/activate
 def main():
     print 'Hello, World!'
from setuptools import setup, find_packages
setup(
    name='hello',
    version='0.1',
    entry_points = {
        'console_scripts': ['hello = hello.main:main']
    },
    packages=find_packages(exclude=['ez_setup']),
    install_requires=[
        'nose'
    ],
)

From here, we’re pretty much set. You can run python setup.py to have more information on how to manipulate your package. Remember to always do that while being in your virtual python environment. To easily work on your project, you can do the following command:

python setup.py develop

It will prepare your package exactly like if you were installing it, but will reference directly your python code with symlink. This way, you can easily test your code while working on it, without having to reinstall everytime.

To distribute your package, simply do the following command:

python setup.py sdist

It will create a .tar.gz in the dist/ subdirectory.

There are many other possibilities. Executing python setup.py can give you a lot more information. The default sdist tarball doesn’t provide a virtual env script which is not practical. It’s possible to create a custom version of virtualenv do distribute along your package, allowing extremely easy installtion.