Thursday, February 10, 2011

Getting Started with Distutils

Distutils is such a wonderful tool. It makes installation of Python modules, packages so easy. Here I'm gonna show you how to write a simple setup.py file, which is required by distutils.

setup.py
from distutils.core import setup
import os
import glob

pyfiles = glob.glob("*.py")
pyfiles = [pyfile[:-3] for pyfile in pyfiles]
setup(name='mymodule',
      version='1.0',
      py_modules=pyfiles,
      packages=['test.test1', 'abc.def'],
      package_dir={'abc.def':'mypackage/abc/def'})
Since setup.py is basically just a Python script, we can do pretty much anything with it. What this script is trying to do is it will copy all the python files in the root directory as well as the some python packages in the test.test1 and abc.def. The directory structure is like this:
root
 |--- test/__init__.py
 |--------/test1/__init__.py
 |--------------/mypackage1.py
 |--------------/mypackage2.py
 |--- mypackage/abc/__init__.py
 |-----------------/def/__init__.py
 |---------------------/mypackage3.py
 |--- mymodule1.py
 |--- mymodule2.py
 |--- mymodule3.py
As we can see mypackage is not part of package name (there isn't any __init__.py file there), thus we need package_dir={'abc.def':'mypackage/abc/def'} in the setup() function.

To build a source distribution:
python setup.py sdist
To build Linux RPM:
python setup.py bdist_prm
To build Windows MSI:
python setup.py bdist_msi
To build Windows installer:
python setup.py bdist_wininst

To install to the default Python installation:
python setup.py install
To install to a particular location:
python setup.py install --prefix=/home/whoever/wherever

No comments:

Post a Comment