Introduction to Python pydoc and distutils

Source: Internet
Author: User
This article mainly introduces the pydoc module and distutils module in Python. This article is from the IBM official Developer Technical Documentation. For more information, see Pydoc

Ka-Ping Yee once created a very famous module named pydoc (in comparison, pydoc can do anything perldoc can do, and do better and more beautiful :-). For Python 2.1, pydoc (and the inspect it supports) is part of the standard library. For users using Python 1.5.2, 1.6, or 2.0, it is also easy to download and install pydoc-please download it now (see references ).

As a background for any beginner reading this Python article, Python has always had some semi-formal documentation standards. These standards do not try to restrict developers excessively, but provide developers with "an obvious way to write documents ." Fortunately, Python developers generally write much better documentation than typical developers in other languages.

The main reason why the Python Documentation is "excellent" is the use of the so-called "docstring ". Although docstring is actually a variable called _ doc _, there is still a common way to create them: you only need to put a simple string enclosed by (triple) quotation marks in the header of the module, function def, class definition, or method def. In addition, several module-level "magic" variable names that are close to the standard are frequently used. Although the document rules are not formal, documents of almost all third-party modules and standard modules use the same pattern. Let's look at a simplified example of using most elements:
Listing 1: module mymod. py with a typical document

#!/usr/bin/python"""Show off features of [pydoc] moduleThis is a silly module todemonstrate docstrings"""__author__ = 'David Mertz'__version__= '1.0'__nonsense__ = 'jabberwocky'class MyClass:  """Demonstrate class docstrings"""  def __init__ (self, spam=1, eggs=2):    """Set default attribute values only    Keyword arguments:    spam ― a processed meat product    eggs ― a fine breakfast for lumberjacks    """    self.spam = spam    self.eggs = eggs

The pydoc module utilizes the Python Documentation Conventions and uses some practical knowledge about Python import, inheritance, and other similar. In addition, pydoc has an absolute talent that can be used in different operation modes (more information about this argument can be seen immediately ). Let's take a look at the manpage style usage called through the OS command line at some time.

Assume that you have installed the above module mymod on your system, but you do not know how useful it is (not much in the example ). You can read the source code, but the simpler method may be:
Listing 2: Getting a 'manpage' document

% pydoc.py mymodPython Library Documentation: module mymodNAME  mymod - Show off features of [pydoc] moduleFILE  /articles/scratch/cp18/mymod.pyDESCRIPTION  This is a silly module to  demonstrate docstringsCLASSES  MyClass  class MyClass   | Demonstrate class docstrings   |   | __init__(self, spam=1, eggs=2)   |   Set default attribute values only   |   |   Keyword arguments:   |   spam ― a processed meat product   |   eggs ― a fine breakfast for lumberjacksDATA  __author__ = 'David Mertz'  __file__ = './mymod.pyc'  __name__ = 'mymod'  __nonsense__ = 'jabberwocky'  __version__ = '1.0'VERSION  1.0AUTHOR  David Mertz

Based on the specific platform and installation process, the above sample may be displayed in a text viewer that allows scrolling, searching, and other functions and highlights certain keywords. For a simple example like this, it is better than simply reading the source code. However, consider the following simple example:
Listing 3: Check the class inheritance structure

% cat mymod2.pyfrom mymod import MyClassclass MyClass2(MyClass):  """Child class"""  def foo(self):    pass% pydoc.py mymod2.MyClass2Python Library Documentation: class MyClass2 in mymod2class MyClass2(mymod.MyClass) | Child class | | __init__(self, spam=1, eggs=2) from mymod.MyClass | | foo(self)

In this quick report, we can know that MyClass2 has the _ init _ () and foo () methods (and corresponding parameters ), which method is implemented by the class itself and which other methods are inherited (and the position of the inherited class ).

Another wonderful feature similar to manpage is the-k option used to search for keywords in the module. For example:
Listing 4: locate the appropriate module for the task

% pydoc.py -k uuencodeuu - Implementation of the UUencode and UUdecode functions.% pydoc.py uuPython Library Documentation: module uuNAME  uu - Implementation of the UUencode and UUdecode functions.[...]

In addition to its command line usage, pydoc also has four other "modes" to display the generated same document.

Shell mode: in the Python interactive shell, you can import the help () function of pydoc to get help from any object without leaving the interactive session. You can also enter only one help to enter the interactive "help interpreter ". For example:

Listing 5: interactive help interpreter in shell mode

  #------- Interactive shell with help enhancements ------#  >>> from pydoc import help  >>> import uu  >>> help(uu.test)  Help on function test in module uu:  test()   uuencode/uudecode main program  >>> help  Welcome to Python 2.0! This is the online help utility.  [...introductory message about help shell...]  help>

  • Web server mode: only the-p option is used, and pydoc is automatically started on LOCALHOST as a simple Web server. You can use any Web browser to browse all modules installed on the existing operating system. The home page of this server is a list of modules that are grouped by Directories (with eye-catching color blocks supported by browsers. In addition, each module you view its documentation is also widely distributed with its imported functions, methods, and links to any module.
  • HTML builder mode:-w option can generate HTML document pages for any document that pydoc can archive. These pages are essentially the same as the pages you may browse in Web server mode, but the pages are static and can be archived and transmitted.
  • TK browser mode: The-g option will create a "graphic help browser" that is similar to xman or tkman ."

Distutils

For Python 1.6, the distutils package has become part of the standard Python library. The distutils package has two purposes. On the one hand, distutils hopes to make end users feel that the process of installing new modules, packages and tools is consistent and easy. On the other hand, distutils also hopes that developers of new modules, packages and tools can easily create these easy-to-install distribution packages. Let's take a brief look at these two aspects.

In the simplest case, the developer has chosen to create an installer for your specific platform. In this case, you do not need to know the existence of distutils. Currently, distutils can create RPM for Linux systems that support RPM and Windows EXE installer for Win32 systems. Although these two platforms are the main character, there are still other platforms, or developers may already have solutions for your platform (or create a time and interest for installing a program ).

Although there is no simple example, fortunately the next outstanding example is not too complex. Suppose you have obtained a source code distribution package that supports distutils, you can rely on a lot of things (of course, in all normal cases ). The archive file of the distribution package must follow the standard archive file format-usually yes. zip format or. tgz/.tar.gz format (occasionally. tbz format or tar. Z format ,. the sit format can be added to MacOS soon ). Most of the time, Windows users use zip files, while Linux/UNIX users use tarball files. However, it is not difficult to parse most file formats on most platforms. Once you unpackage an archive file, you will get a collection of files that are saved in a directory with the same name as the archive file. For example:
Listing 6: unpackage a [distutils] archive file

E:\Archive\devel>unzip -q Distutils-1_0_2.zipE:\Archive\devel>cd Distutils-1.0.2E:\Archive\devel\Distutils-1.0.2>lsThe volume label in drive E is ARCHIVE.The Volume Serial Number is E825:C814.Directory of E:\Archive\devel\Distutils-1.0.2 6-14-01  0:38a   
 
        0 . 6-14-01  0:38a   
  
         0 .. 5-03-01  6:30p   15355      0 CHANGES.txt 5-03-01  6:32p   
   
          0 distutils 5-03-01  6:32p   
    
           0 doc 5-03-01  6:32p   
     
            0 examples10-02-00 11:47p    373      0 MANIFEST.in 5-03-01  6:32p   
      
        0 misc 5-03-01 6:32p 496 0 PKG-INFO 4-20-01 2:30p 14407 0 README.txt 6-29-00 11:45p 1615 0 setup.cfg 5-03-01 6:17p 1120 0 setup.py 4-20-01 2:29p 9116 0 TODO 4-11-00 9:40p 836 0 USAGE.txt
      
     
    
   
  
 

Most module distribution packages have fewer files and directories than shown in this example. All you really need is the setup. py file, which contains the installation command. But in fact, we all wanted other files in the directory, so setup. py had something to install. Here, what you need to do is:

  E:\archive\devel\Distutils-1.0.2> python setup.py install

At least that should be what you should do. If any problem occurs, read the README.txt or README file (which may also be included in setup. py. Then, read Greg Ward's Installing Python Modules document. (See references ).

What should we do next? You can guess by name that setup. py is actually just a normal Python script, so it can do anything when it runs. However, in most cases, setup. py has a fixed format. It may look like this:
Listing 7: the minimal setup. py installation script

#!/usr/bin/env python"""Setup script for the sample #1 module distribution:  single top-level pure Python module, named explicitly  in 'py_modules'."""from distutils.core import setupsetup (# Distribution meta-data    name = "sample",    version = "1.0",    description = "Distutils sample distribution #1",# Description of modules and packages in the distribution    py_modules = ['sample'],   )

The real work here is implemented by the imported distutils, especially by the setup () function. Basically, the setup () function uses a set of named variables that contain a column of things to be installed (besides py_modules, there may be packages, ext_modules, or other things.

The magic of distutils is to create a module distribution package using the identical setup. py file used during installation. Once you create a setup. py script (or 'Setup. cfg 'or other extensions) specifies what needs to be installed. all you need to do to create a distribution package is (one or several steps below ):
Listing 8: Creating a module distribution package

% python setup.py sdist% python setup.py bdist_wininst% python setup.py bdist_rpm

Based on the specified distribution package, you will create a standard archive file (tarball or zip files, depending on the platform type) or a complete installer (as discussed above ).

Combine the two

Although we haven't fully achieved our goal yet, Python has gradually become one of the most easy-to-use programming languages and one of the most easy-to-use programming communities. Although some new tools still have some shortcomings to overcome, in the general sense, the requirement to make Python transparent to users has been realized.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.