Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - Custom distutils commands

I have a library called "example" that I'm installing into my global site-packages directory. However, I'd like to be able to install two versions, one for production and one for testing (I have a web application and other things that are versioned this way).

Is there a way to specify, say "python setup.py stage" that will not only install a different egg into site-packages, but also rename the module from "example" to "example_stage" or something similar?

If distutils cannot do this, is there any other tool that can?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can easily be done with distutils by subclassing distutils.core.Command inside of setup.py.

For example:

from distutils.core import setup, Command
import os, sys

class CleanCommand(Command):
    description = "custom clean command that forcefully removes dist/build directories"
    user_options = []
    def initialize_options(self):
        self.cwd = None
    def finalize_options(self):
        self.cwd = os.getcwd()
    def run(self):
        assert os.getcwd() == self.cwd, 'Must be in package root: %s' % self.cwd
        os.system('rm -rf ./build ./dist')  

To enable the command you must reference it in setup():

setup(
     # stuff omitted for conciseness.
     cmdclass={
        'clean': CleanCommand
}

Note that you can override built-in commands this way too, such as what I did with 'clean'. (I didn't like how the built-in version left behind the 'dist' and 'build' directories.)

% python setup.py --help-commands | grep clean
  clean            custom clean command that forcefully removes dist/build dirs.

There are a number of conventions that are used:

  • You specify any command-line arguments with user_options.
  • You declare any variables you would use with the initialize_options() method, which is called after initialization to setup your custom namespace for the subclass.
  • The finalize_options() method is called right before run().
  • The guts of the command itself will occur in run() so be sure to do any other prep work before that.

The best example to use is just to look at the source code for one of the default commands found at PYTHON_DIR/distutils/command such as install.py or build.py.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...