Links
setup.cfg filespyproject.toml filespkg_resourcesProject
setup() Keywordsdependency_linkszip_safe flagsetuptools commandsSee also
Thesetuptools project adds new capabilities to thesetup functionand other APIs, makes the API consistent across different Python versions,and is hence recommended over usingdistutils directly.
Note
This document is being retained solely until thesetuptools documentationathttps://setuptools.pypa.io/en/latest/setuptools.htmlindependently covers all of the relevant information currently included here.
distutils.core — Core Distutils functionality¶Thedistutils.core module is the only module that needs to be installedto use the Distutils. It provides thesetup() (which is called from thesetup script). Indirectly provides thedistutils.dist.Distribution anddistutils.cmd.Command class.
The basic do-everything function that does most everything you could ever askfor from a Distutils method.
The setup function takes a large number of arguments. These are laid out in thefollowing table.
argument name | value | type |
|---|---|---|
name | The name of the package | a string |
version | The version number of thepackage; see | a string |
description | A single line describing thepackage | a string |
long_description | Longer description of thepackage | a string |
author | The name of the package author | a string |
author_email | The email address of thepackage author | a string |
maintainer | The name of the currentmaintainer, if different fromthe author. Note that ifthe maintainer is provided,distutils will use it as theauthor in | a string |
maintainer_email | The email address of thecurrent maintainer, ifdifferent from the author | a string |
url | A URL for the package(homepage) | a string |
download_url | A URL to download the package | a string |
packages | A list of Python packages thatdistutils will manipulate | a list of strings |
py_modules | A list of Python modules thatdistutils will manipulate | a list of strings |
scripts | A list of standalone scriptfiles to be built andinstalled | a list of strings |
ext_modules | A list of Python extensions tobe built | a list of instances of |
classifiers | A list of categories for thepackage | a list of strings; valid classifiers are listed onPyPI. |
distclass | the | a subclass of |
script_name | The name of the setup.pyscript - defaults to | a string |
script_args | Arguments to supply to thesetup script | a list of strings |
options | default options for the setupscript | a dictionary |
license | The license for the package | a string |
keywords | Descriptive meta-data, seePEP 314 | a list of strings or a comma-separated string |
platforms | a list of strings or a comma-separated string | |
cmdclass | A mapping of command names to | a dictionary |
data_files | A list of data files toinstall | a list |
package_dir | A mapping of package todirectory names | a dictionary |
Run a setup script in a somewhat controlled environment, and return thedistutils.dist.Distribution instance that drives things. This isuseful if you need to find out the distribution meta-data (passed as keywordargs fromscript tosetup()), or the contents of the config files orcommand-line.
script_name is a file that will be read and run withexec().sys.argv[0]will be replaced withscript for the duration of the call.script_args is alist of strings; if supplied,sys.argv[1:] will be replaced byscript_argsfor the duration of the call.
stop_after tellssetup() when to stop processing; possible values:
value | description |
|---|---|
init | Stop after the |
config | Stop after config files have been parsed(and their data stored in the |
commandline | Stop after the command-line( |
run | Stop after all commands have been run (thesame as if |
In addition, thedistutils.core module exposed a number of classes thatlive elsewhere.
Extension fromdistutils.extension
Command fromdistutils.cmd
Distribution fromdistutils.dist
A short description of each of these follows, but see the relevant module forthe full reference.
The Extension class describes a single C or C++ extension module in a setupscript. It accepts the following keyword arguments in its constructor:
argument name | value | type |
|---|---|---|
name | the full name of theextension, including anypackages — ie.not afilename or pathname, butPython dotted name | a string |
sources | list of source filenames,relative to the distributionroot (where the setup scriptlives), in Unix form(slash-separated) forportability.Source files may be C, C++,SWIG (.i), platform-specificresource files, or whateverelse is recognized by thebuild_ext commandas source for a Pythonextension. | a list of strings |
include_dirs | list of directories to searchfor C/C++ header files (inUnix form for portability) | a list of strings |
define_macros | list of macros to define; eachmacro is defined using a2-tuple | a list of tuples |
undef_macros | list of macros to undefineexplicitly | a list of strings |
library_dirs | list of directories to searchfor C/C++ libraries at linktime | a list of strings |
libraries | list of library names (notfilenames or paths) to linkagainst | a list of strings |
runtime_library_dirs | list of directories to searchfor C/C++ libraries at runtime (for shared extensions,this is when the extension isloaded) | a list of strings |
extra_objects | list of extra files to linkwith (eg. object files notimplied by ‘sources’, staticlibrary that must beexplicitly specified, binaryresource files, etc.) | a list of strings |
extra_compile_args | any extra platform- andcompiler-specific informationto use when compiling thesource files in ‘sources’. Forplatforms and compilers wherea command line makes sense,this is typically a list ofcommand-line arguments, butfor other platforms it couldbe anything. | a list of strings |
extra_link_args | any extra platform- andcompiler-specific informationto use when linking objectfiles together to create theextension (or to create a newstatic Python interpreter).Similar interpretation as for‘extra_compile_args’. | a list of strings |
export_symbols | list of symbols to be exportedfrom a shared extension. Notused on all platforms, and notgenerally necessary for Pythonextensions, which typicallyexport exactly one symbol: | a list of strings |
depends | list of files that theextension depends on | a list of strings |
language | extension language (i.e. | a string |
optional | specifies that a build failurein the extension should notabort the build process, butsimply skip the extension. | a boolean |
Changed in version 3.8:On Unix, C extensions are no longer linked to libpython except onAndroid and Cygwin.
ADistribution describes how to build, install and package up a Pythonsoftware package.
See thesetup() function for a list of keyword arguments accepted by theDistribution constructor.setup() creates a Distribution instance.
Changed in version 3.7:Distribution now warns ifclassifiers,keywords andplatforms fields are not specified as a list ora string.
distutils.ccompiler — CCompiler base class¶This module provides the abstract base class for theCCompilerclasses. ACCompiler instance can be used for all the compile andlink steps needed to build a single project. Methods are provided to setoptions for the compiler — macro definitions, include directories, link path,libraries and the like.
This module provides the following functions.
Generate linker options for searching library directories and linking withspecific libraries.libraries andlibrary_dirs are, respectively, lists oflibrary names (not filenames!) and search directories. Returns a list ofcommand-line options suitable for use with some compiler (depending on the twoformat strings passed in).
Generate C pre-processor options (-D,-U,-I) asused by at least two types of compilers: the typical Unix compiler and VisualC++.macros is the usual thing, a list of 1- or 2-tuples, where(name,)means undefine (-U) macroname, and(name,value) means define(-D) macroname tovalue.include_dirs is just a list ofdirectory names to be added to the header file search path (-I).Returns a list of command-line options suitable for either Unix compilers orVisual C++.
Determine the default compiler to use for the given platform.
osname should be one of the standard Python OS names (i.e. the ones returnedbyos.name) andplatform the common value returned bysys.platform forthe platform in question.
The default values areos.name andsys.platform in case the parametersare not given.
Factory function to generate an instance of some CCompiler subclass for thesupplied platform/compiler combination.plat defaults toos.name (eg.'posix','nt'), andcompiler defaults to the default compiler forthat platform. Currently only'posix' and'nt' are supported, and thedefault compilers are “traditional Unix interface” (UnixCCompilerclass) and Visual C++ (MSVCCompiler class). Note that it’s perfectlypossible to ask for a Unix compiler object under Windows, and a Microsoftcompiler object under Unix—if you supply a value forcompiler,plat isignored.
Print list of available compilers (used by the--help-compiler optionstobuild,build_ext,build_clib).
The abstract base classCCompiler defines the interface that must beimplemented by real compiler classes. The class also has some utility methodsused by several compiler classes.
The basic idea behind a compiler abstraction class is that each instance can beused for all the compile/link steps in building a single project. Thus,attributes common to all of those compile and link steps — includedirectories, macros to define, libraries to link against, etc. — areattributes of the compiler instance. To allow for variability in how individualfiles are treated, most of those attributes may be varied on a per-compilationor per-link basis.
The constructor for each subclass creates an instance of the Compiler object.Flags areverbose (show verbose output),dry_run (don’t actually execute thesteps) andforce (rebuild everything, regardless of dependencies). All ofthese flags default to0 (off). Note that you probably don’t want toinstantiateCCompiler or one of its subclasses directly - use thedistutils.CCompiler.new_compiler() factory function instead.
The following methods allow you to manually alter compiler options for theinstance of the Compiler class.
Adddir to the list of directories that will be searched for header files.The compiler is instructed to search directories in the order in which they aresupplied by successive calls toadd_include_dir().
Set the list of directories that will be searched todirs (a list of strings).Overrides any preceding calls toadd_include_dir(); subsequent calls toadd_include_dir() add to the list passed toset_include_dirs().This does not affect any list of standard include directories that the compilermay search by default.
Addlibname to the list of libraries that will be included in all links drivenby this compiler object. Note thatlibname should *not* be the name of afile containing a library, but the name of the library itself: the actualfilename will be inferred by the linker, the compiler, or the compiler class(depending on the platform).
The linker will be instructed to link against libraries in the order they weresupplied toadd_library() and/orset_libraries(). It is perfectlyvalid to duplicate library names; the linker will be instructed to link againstlibraries as many times as they are mentioned.
Set the list of libraries to be included in all links driven by this compilerobject tolibnames (a list of strings). This does not affect any standardsystem libraries that the linker may include by default.
Adddir to the list of directories that will be searched for librariesspecified toadd_library() andset_libraries(). The linker will beinstructed to search for libraries in the order they are supplied toadd_library_dir() and/orset_library_dirs().
Set the list of library search directories todirs (a list of strings). Thisdoes not affect any standard library search path that the linker may search bydefault.
Adddir to the list of directories that will be searched for shared librariesat runtime.
Set the list of directories to search for shared libraries at runtime todirs(a list of strings). This does not affect any standard search path that theruntime linker may search by default.
Define a preprocessor macro for all compilations driven by this compiler object.The optional parametervalue should be a string; if it is not supplied, thenthe macro will be defined without an explicit value and the exact outcomedepends on the compiler used.
Undefine a preprocessor macro for all compilations driven by this compilerobject. If the same macro is defined bydefine_macro() andundefined byundefine_macro() the last call takes precedence(including multiple redefinitions or undefinitions). If the macro isredefined/undefined on a per-compilation basis (ie. in the call tocompile()), then that takes precedence.
Addobject to the list of object files (or analogues, such as explicitly namedlibrary files or the output of “resource compilers”) to be included in everylink driven by this compiler object.
Set the list of object files (or analogues) to be included in every link toobjects. This does not affect any standard object files that the linker mayinclude by default (such as system libraries).
The following methods implement methods for autodetection of compiler options,providing some functionality similar to GNUautoconf.
Detect the language of a given file, or list of files. Uses the instanceattributeslanguage_map (a dictionary), andlanguage_order (alist) to do the job.
Search the specified list of directories for a static or shared library filelib and return the full path to that file. Ifdebug is true, look for adebugging version (if that makes sense on the current platform). ReturnNone iflib wasn’t found in any of the specified directories.
Return a boolean indicating whetherfuncname is supported on the currentplatform. The optional arguments can be used to augment the compilationenvironment by providing additional include files and paths and libraries andpaths.
Return the compiler option to adddir to the list of directories searched forlibraries.
Return the compiler option to addlib to the list of libraries linked into theshared library or executable.
Return the compiler option to adddir to the list of directories searched forruntime libraries.
Define the executables (and options for them) that will be run to perform thevarious stages of compilation. The exact set of executables that may bespecified here depends on the compiler class (via the ‘executables’ classattribute), but most will have:
attribute | description |
|---|---|
compiler | the C/C++ compiler |
linker_so | linker used to create shared objects andlibraries |
linker_exe | linker used to create binary executables |
archiver | static library creator |
On platforms with a command-line (Unix, DOS/Windows), each of these is a stringthat will be split into executable name and (optional) list of arguments.(Splitting the string is done similarly to how Unix shells operate: words aredelimited by spaces, but quotes and backslashes can override this. Seedistutils.util.split_quoted().)
The following methods invoke stages in the build process.
Compile one or more source files. Generates object files (e.g. transforms a.c file to a.o file.)
sources must be a list of filenames, most likely C/C++ files, but in realityanything that can be handled by a particular compiler and compiler class (eg.MSVCCompiler can handle resource files insources). Return a list ofobject filenames, one per source filename insources. Depending on theimplementation, not all source files will necessarily be compiled, but allcorresponding object filenames will be returned.
Ifoutput_dir is given, object files will be put under it, while retainingtheir original path component. That is,foo/bar.c normally compiles tofoo/bar.o (for a Unix implementation); ifoutput_dir isbuild, thenit would compile tobuild/foo/bar.o.
macros, if given, must be a list of macro definitions. A macro definition iseither a(name,value) 2-tuple or a(name,) 1-tuple. The former definesa macro; if the value isNone, the macro is defined without an explicitvalue. The 1-tuple case undefines a macro. Laterdefinitions/redefinitions/undefinitions take precedence.
include_dirs, if given, must be a list of strings, the directories to add tothe default include file search path for this compilation only.
debug is a boolean; if true, the compiler will be instructed to output debugsymbols in (or alongside) the object file(s).
extra_preargs andextra_postargs are implementation-dependent. On platformsthat have the notion of a command-line (e.g. Unix, DOS/Windows), they are mostlikely lists of strings: extra command-line arguments to prepend/append to thecompiler command line. On other platforms, consult the implementation classdocumentation. In any event, they are intended as an escape hatch for thoseoccasions when the abstract compiler framework doesn’t cut the mustard.
depends, if given, is a list of filenames that all targets depend on. If asource file is older than any file in depends, then the source file will berecompiled. This supports dependency tracking, but only at a coarsegranularity.
RaisesCompileError on failure.
Link a bunch of stuff together to create a static library file. The “bunch ofstuff” consists of the list of object files supplied asobjects, the extraobject files supplied toadd_link_object() and/orset_link_objects(), the libraries supplied toadd_library() and/orset_libraries(), and the libraries supplied aslibraries (if any).
output_libname should be a library name, not a filename; the filename will beinferred from the library name.output_dir is the directory where the libraryfile will be put.
debug is a boolean; if true, debugging information will be included in thelibrary (note that on most platforms, it is the compile step where this matters:thedebug flag is included here just for consistency).
target_lang is the target language for which the given objects are beingcompiled. This allows specific linkage time treatment of certain languages.
RaisesLibError on failure.
Link a bunch of stuff together to create an executable or shared library file.
The “bunch of stuff” consists of the list of object files supplied asobjects.output_filename should be a filename. Ifoutput_dir is supplied,output_filename is relative to it (i.e.output_filename can providedirectory components if needed).
libraries is a list of libraries to link against. These are library names,not filenames, since they’re translated into filenames in a platform-specificway (eg.foo becomeslibfoo.a on Unix andfoo.lib onDOS/Windows). However, they can include a directory component, which means thelinker will look in that specific directory rather than searching all the normallocations.
library_dirs, if supplied, should be a list of directories to search forlibraries that were specified as bare library names (ie. no directorycomponent). These are on top of the system default and those supplied toadd_library_dir() and/orset_library_dirs().runtime_library_dirsis a list of directories that will be embedded into the shared library and usedto search for other shared libraries that *it* depends on at run-time. (Thismay only be relevant on Unix.)
export_symbols is a list of symbols that the shared library will export.(This appears to be relevant only on Windows.)
debug is as forcompile() andcreate_static_lib(), with theslight distinction that it actually matters on most platforms (as opposed tocreate_static_lib(), which includes adebug flag mostly for form’ssake).
extra_preargs andextra_postargs are as forcompile() (except ofcourse that they supply command-line arguments for the particular linker beingused).
target_lang is the target language for which the given objects are beingcompiled. This allows specific linkage time treatment of certain languages.
RaisesLinkError on failure.
Link an executable.output_progname is the name of the file executable, whileobjects are a list of object filenames to link in. Other arguments are as forthelink() method.
Link a shared library.output_libname is the name of the output library,whileobjects is a list of object filenames to link in. Other arguments areas for thelink() method.
Link a shared object.output_filename is the name of the shared object thatwill be created, whileobjects is a list of object filenames to link in.Other arguments are as for thelink() method.
Preprocess a single C/C++ source file, named insource. Output will be writtento file namedoutput_file, orstdout ifoutput_file not supplied.macros is a list of macro definitions as forcompile(), which willaugment the macros set withdefine_macro() andundefine_macro().include_dirs is a list of directory names that will be added to the defaultlist, in the same way asadd_include_dir().
RaisesPreprocessError on failure.
The following utility methods are defined by theCCompiler class, foruse by the various concrete subclasses.
Returns the filename of the executable for the givenbasename. Typically fornon-Windows platforms this is the same as the basename, while Windows will geta.exe added.
Returns the filename for the given library name on the current platform. On Unixa library withlib_type of'static' will typically be of the formliblibname.a, while alib_type of'dynamic' will be of the formliblibname.so.
Returns the name of the object files for the given source files.source_filenames should be a list of filenames.
Returns the name of a shared object file for the given file namebasename.
Invokesdistutils.util.execute(). This method invokes a Python functionfunc with the given argumentsargs, after logging and taking into accountthedry_run flag.
Invokesdistutils.spawn.spawn(). This invokes an external process to runthe given command.
Invokesdistutils.dir_util.mkpath(). This creates a directory and anymissing ancestor directories.
Invokesdistutils.file_util.move_file(). Renamessrc todst.
Write a message usingdistutils.log.debug().
Write a warning messagemsg to standard error.
distutils.unixccompiler — Unix C Compiler¶This module provides theUnixCCompiler class, a subclass ofCCompiler that handles the typical Unix-style command-line C compiler:
macros defined with-Dname[=value]
macros undefined with-Uname
include search directories specified with-Idir
libraries specified with-llib
library search directories specified with-Ldir
compile handled bycc (or similar) executable with-coption: compiles.c to.o
link static library handled byar command (possibly withranlib)
link shared library handled bycc-shared
distutils.msvccompiler — Microsoft Compiler¶This module providesMSVCCompiler, an implementation of the abstractCCompiler class for Microsoft Visual Studio. Typically, extensionmodules need to be compiled with the same compiler that was used to compilePython. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python2.4 and 2.5, the compiler is Visual Studio .NET 2003.
MSVCCompiler will normally choose the right compiler, linker etc. onits own. To override this choice, the environment variablesDISTUTILS_USE_SDKandMSSdk must be both set.MSSdk indicates that the current environment hasbeen setup by the SDK’sSetEnv.Cmd script, or that the environment variableshad been registered when the SDK was installed;DISTUTILS_USE_SDK indicatesthat the distutils user has made an explicit choice to override the compilerselection byMSVCCompiler.
distutils.bcppcompiler — Borland Compiler¶This module providesBorlandCCompiler, a subclass of the abstractCCompiler class for the Borland C++ compiler.
distutils.cygwinccompiler — Cygwin Compiler¶This module provides theCygwinCCompiler class, a subclass ofUnixCCompiler that handles the Cygwin port of the GNU C compiler toWindows. It also contains the Mingw32CCompiler class which handles the mingw32port of GCC (same as cygwin in no-cygwin mode).
distutils.archive_util — Archiving utilities¶This module provides a few functions for creating archive files, such astarballs or zipfiles.
Create an archive file (eg.zip ortar).base_name is the name ofthe file to create, minus any format-specific extension;format is thearchive format: one ofzip,tar,gztar,bztar,xztar, orztar.root_dir is a directory that will be the root directory of thearchive; ie. we typicallychdir intoroot_dir before creating thearchive.base_dir is the directory where we start archiving from; ie.base_dir will be the common prefix of all files and directories in thearchive.root_dir andbase_dir both default to the current directory.Returns the name of the archive file.
Changed in version 3.5:Added support for thexztar format.
‘Create an (optional compressed) archive as a tar file from all files in andunderbase_dir.compress must be'gzip' (the default),'bzip2','xz','compress', orNone. For the'compress'method the compression utility named bycompress must be on thedefault program search path, so this is probably Unix-specific. The outputtar file will be namedbase_dir.tar, possibly plus the appropriatecompression extension (.gz,.bz2,.xz or.Z). Return theoutput filename.
Changed in version 3.5:Added support for thexz compression.
Create a zip file from all files in and underbase_dir. The output zip filewill be namedbase_name +.zip. Uses either thezipfile Pythonmodule (if available) or the InfoZIPzip utility (if installed andfound on the default search path). If neither tool is available, raisesDistutilsExecError. Returns the name of the output zip file.
distutils.dep_util — Dependency checking¶This module provides functions for performing simple, timestamp-baseddependency of files and groups of files; also, functions based entirely on suchtimestamp dependency analysis.
Return true ifsource exists and is more recently modified thantarget, orifsource exists andtarget doesn’t. Return false if both exist andtargetis the same age or newer thansource. RaiseDistutilsFileError ifsource does not exist.
Walk two filename lists in parallel, testing if each source is newer than itscorresponding target. Return a pair of lists (sources,targets) wheresource is newer than target, according to the semantics ofnewer().
Return true iftarget is out-of-date with respect to any file listed insources. In other words, iftarget exists and is newer than every file insources, return false; otherwise return true.missing controls what we dowhen a source file is missing; the default ('error') is to blow up with anOSError from insideos.stat(); if it is'ignore', we silentlydrop any missing source files; if it is'newer', any missing source filesmake us assume thattarget is out-of-date (this is handy in “dry-run” mode:it’ll make you pretend to carry out commands that wouldn’t work because inputsare missing, but that doesn’t matter because you’re not actually going to runthe commands).
distutils.dir_util — Directory tree operations¶This module provides functions for operating on directories and trees ofdirectories.
Create a directory and any missing ancestor directories. If the directoryalready exists (or ifname is the empty string, which means the currentdirectory, which of course exists), then do nothing. RaiseDistutilsFileError if unable to create some directory along the way (eg.some sub-path exists, but is a file rather than a directory). Ifverbose istrue, print a one-line summary of each mkdir to stdout. Return the list ofdirectories actually created.
Create all the empty directories underbase_dir needed to putfiles there.base_dir is just the name of a directory which doesn’t necessarily existyet;files is a list of filenames to be interpreted relative tobase_dir.base_dir + the directory portion of every file infiles will be created ifit doesn’t already exist.mode,verbose anddry_run flags are as formkpath().
Copy an entire directory treesrc to a new locationdst. Bothsrc anddst must be directory names. Ifsrc is not a directory, raiseDistutilsFileError. Ifdst does not exist, it is created withmkpath(). The end result of the copy is that every file insrc iscopied todst, and directories undersrc are recursively copied todst.Return the list of files that were copied or might have been copied, using theiroutput name. The return value is unaffected byupdate ordry_run: it issimply the list of all files undersrc, with the names changed to be underdst.
preserve_mode andpreserve_times are the same as fordistutils.file_util.copy_file(); note that they only apply toregular files, not todirectories. Ifpreserve_symlinks is true, symlinks will be copied assymlinks (on platforms that support them!); otherwise (the default), thedestination of the symlink will be copied.update andverbose are the sameas forcopy_file().
Files insrc that begin with.nfs are skipped (more information onthese files is available in answer D2 of theNFS FAQ page).
Changed in version 3.3.1:NFS files are ignored.
Recursively removedirectory and all files and directories underneath it. Anyerrors are ignored (apart from being reported tosys.stdout ifverbose istrue).
distutils.file_util — Single file operations¶This module contains some utility functions for operating on individual files.
Copy filesrc todst. Ifdst is a directory, thensrc is copied therewith the same name; otherwise, it must be a filename. (If the file exists, itwill be ruthlessly clobbered.) Ifpreserve_mode is true (the default), thefile’s mode (type and permission bits, or whatever is analogous on thecurrent platform) is copied. Ifpreserve_times is true (the default), thelast-modified and last-access times are copied as well. Ifupdate is true,src will only be copied ifdst does not exist, or ifdst does exist butis older thansrc.
link allows you to make hard links (usingos.link()) or symbolic links(usingos.symlink()) instead of copying: set it to'hard' or'sym'; if it isNone (the default), files are copied. Don’t setlinkon systems that don’t support it:copy_file() doesn’t check if hard orsymbolic linking is available. It uses_copy_file_contents() to copy filecontents.
Return a tuple(dest_name,copied):dest_name is the actual name of theoutput file, andcopied is true if the file was copied (or would have beencopied, ifdry_run true).
Move filesrc todst. Ifdst is a directory, the file will be moved intoit with the same name; otherwise,src is just renamed todst. Returns thenew full name of the file.
Warning
Handles cross-device moves on Unix usingcopy_file(). What aboutother systems?
Create a file calledfilename and writecontents (a sequence of stringswithout line terminators) to it.
distutils.util — Miscellaneous other utility functions¶This module contains other assorted bits and pieces that don’t fit into anyother utility module.
Return a string that identifies the current platform. This is used mainly todistinguish platform-specific build directories and platform-specific builtdistributions. Typically includes the OS name and version and thearchitecture (as supplied by ‘os.uname()’), although the exact informationincluded depends on the OS; e.g., on Linux, the kernel version isn’tparticularly important.
Examples of returned values:
linux-i586
linux-alpha
solaris-2.6-sun4u
For non-POSIX platforms, currently just returnssys.platform.
For Mac OS X systems the OS version reflects the minimal version on whichbinaries will run (that is, the value ofMACOSX_DEPLOYMENT_TARGETduring the build of Python), not the OS version of the current system.
For universal binary builds on Mac OS X the architecture value reflectsthe universal binary status instead of the architecture of the currentprocessor. For 32-bit universal binaries the architecture isfat,for 64-bit universal binaries the architecture isfat64, andfor 4-way universal binaries the architecture isuniversal. Startingfrom Python 2.7 and Python 3.2 the architecturefat3 is used fora 3-way universal build (ppc, i386, x86_64) andintel is used fora universal build with the i386 and x86_64 architectures
Examples of returned values on Mac OS X:
macosx-10.3-ppc
macosx-10.3-fat
macosx-10.5-universal
macosx-10.6-intel
For AIX, Python 3.9 and later return a string starting with “aix”, followedby additional fields (separated by'-') that represent the combinedvalues of AIX Version, Release and Technology Level (first field), Build Date(second field), and bit-size (third field). Python 3.8 and earlier returnedonly a single additional field with the AIX Version and Release.
Examples of returned values on AIX:
aix-5307-0747-32 # 32-bit build on AIXoslevel-s: 5300-07-00-0000
aix-7105-1731-64 # 64-bit build on AIXoslevel-s: 7100-05-01-1731
aix-7.2 # Legacy form reported in Python 3.8 and earlier
Changed in version 3.9:The AIX platform string format now also includes the technology level,build date, and ABI bit-size.
Return ‘pathname’ as a name that will work on the native filesystem, i.e. splitit on ‘/’ and put it back together again using the current directory separator.Needed because filenames in the setup script are always supplied in Unix style,and have to be converted to the local convention before we can actually use themin the filesystem. RaisesValueError on non-Unix-ish systems ifpathname either starts or ends with a slash.
Returnpathname withnew_root prepended. Ifpathname is relative, this isequivalent toos.path.join(new_root,pathname) Otherwise, it requires makingpathname relative and then joining the two, which is tricky on DOS/Windows.
Ensure that ‘os.environ’ has all the environment variables we guarantee thatusers can use in config files, command-line options, etc. Currently thisincludes:
HOME - user’s home directory (Unix only)
PLAT - description of the current platform, including hardware andOS (seeget_platform())
Perform shell/Perl-style variable substitution ons. Every occurrence of$ followed by a name is considered a variable, and variable is substitutedby the value found in thelocal_vars dictionary, or inos.environ if it’snot inlocal_vars.os.environ is first checked/augmented to guarantee thatit contains certain values: seecheck_environ(). RaiseValueErrorfor any variables not found in eitherlocal_vars oros.environ.
Note that this is not a fully-fledged string interpolation function. A valid$variable can consist only of upper and lower case letters, numbers and anunderscore. No { } or ( ) style quoting is available.
Split a string up according to Unix shell-like rules for quotes and backslashes.In short: words are delimited by spaces, as long as those spaces are not escapedby a backslash, or inside a quoted string. Single and double quotes areequivalent, and the quote characters can be backslash-escaped. The backslash isstripped from any two-character escape sequence, leaving only the escapedcharacter. The quote characters are stripped from any quoted string. Returns alist of words.
Perform some action that affects the outside world (for instance, writing to thefilesystem). Such actions are special because they are disabled by thedry_run flag. This method takes care of all that bureaucracy for you; allyou have to do is supply the function to call and an argument tuple for it (toembody the “external action” being performed), and an optional message to print.
Convert a string representation of truth to true (1) or false (0).
True values arey,yes,t,true,on and1; false valuesaren,no,f,false,off and0. RaisesValueError ifval is anything else.
Byte-compile a collection of Python source files to.pyc files in a__pycache__ subdirectory (seePEP 3147 andPEP 488).py_files is a list of files to compile; any files that don’t end in.py are silently skipped.optimize must be one of the following:
0 - don’t optimize
1 - normal optimization (likepython-O)
2 - extra optimization (likepython-OO)
Ifforce is true, all files are recompiled regardless of timestamps.
The source filename encoded in eachbytecode file defaults to the filenameslisted inpy_files; you can modify these withprefix andbasedir.prefix is a string that will be stripped off of each source filename, andbase_dir is a directory name that will be prepended (afterprefix isstripped). You can supply either or both (or neither) ofprefix andbase_dir, as you wish.
Ifdry_run is true, doesn’t actually do anything that would affect thefilesystem.
Byte-compilation is either done directly in this interpreter process with thestandardpy_compile module, or indirectly by writing a temporary scriptand executing it. Normally, you should letbyte_compile() figure out touse direct compilation or not (see the source for details). Thedirect flagis used by the script generated in indirect mode; unless you know what you’redoing, leave it set toNone.
Changed in version 3.2.3:Create.pyc files with animportmagictag in their name, in a__pycache__ subdirectoryinstead of files without tag in the current directory.
Changed in version 3.5:Create.pyc files according toPEP 488.
distutils.dist — The Distribution class¶This module provides theDistribution class, whichrepresents the module distribution being built/installed/distributed.
distutils.extension — The Extension class¶This module provides theExtension class,used to describe C/C++ extension modules in setup scripts.
distutils.debug — Distutils debug mode¶This module provides the DEBUG flag.
distutils.errors — Distutils exceptions¶Provides exceptions used by the Distutils modules. Note that Distutils modulesmay raise standard exceptions; in particular, SystemExit is usually raised forerrors that are obviously the end-user’s fault (eg. bad command-line arguments).
This module is safe to use infrom...import* mode; it only exportssymbols whose names start withDistutils and end withError.
distutils.fancy_getopt — Wrapper around the standard getopt module¶This module provides a wrapper around the standardgetopt module thatprovides the following additional features:
short and long options are tied together
options have help strings, sofancy_getopt() could potentially create acomplete usage summary
options set attributes of a passed-in object
boolean options can have “negative aliases” — eg. if--quiet isthe “negative alias” of--verbose, then--quiet on thecommand line setsverbose to false.
Wrapper function.options is a list of(long_option,short_option,help_string) 3-tuples as described in the constructor forFancyGetopt.negative_opt should be a dictionary mapping option namesto option names, both the key and value should be in theoptions list.object is an object which will be used to store values (see thegetopt()method of theFancyGetopt class).args is the argument list. Will usesys.argv[1:] if you passNone asargs.
Wrapstext to less thanwidth wide.
The option_table is a list of 3-tuples:(long_option,short_option,help_string)
If an option takes an argument, itslong_option should have'=' appended;short_option should just be a single character, no':' in any case.short_option should beNone if along_option doesn’t have acorrespondingshort_option. All option tuples must have long options.
TheFancyGetopt class provides the following methods:
Parse command-line options in args. Store as attributes onobject.
Ifargs isNone or not supplied, usessys.argv[1:]. Ifobject isNone or not supplied, creates a newOptionDummy instance, storesoption values there, and returns a tuple(args,object). Ifobject issupplied, it is modified in place andgetopt() just returnsargs; inboth cases, the returnedargs is a modified copy of the passed-inargs list,which is left untouched.
Returns the list of(option,value) tuples processed by the previous run ofgetopt() RaisesRuntimeError ifgetopt() hasn’t been calledyet.
Generate help text (a list of strings, one per suggested line of output) fromthe option table for thisFancyGetopt object.
If supplied, prints the suppliedheader at the top of the help.
distutils.filelist — The FileList class¶This module provides theFileList class, used for poking about thefilesystem and building lists of files.
distutils.log — SimplePEP 282-style logging¶distutils.spawn — Spawn a sub-process¶This module provides thespawn() function, afront-end to various platform-specific functions for launching anotherprogram in a sub-process.Also providesfind_executable() to search the path for a given executablename.
distutils.sysconfig — System configuration information¶Thedistutils.sysconfig module provides access to Python’s low-levelconfiguration information. The specific configuration variables availabledepend heavily on the platform and configuration. The specific variables dependon the build process for the specific version of Python being run; the variablesare those found in theMakefile and configuration header that areinstalled with Python on Unix systems. The configuration header is calledpyconfig.h for Python versions starting with 2.2, andconfig.hfor earlier versions of Python.
Some additional functions are provided which perform some useful manipulationsfor other parts of thedistutils package.
The result ofos.path.normpath(sys.prefix).
The result ofos.path.normpath(sys.exec_prefix).
Return the value of a single variable. This is equivalent toget_config_vars().get(name).
Return a set of variable definitions. If there are no arguments, this returns adictionary mapping names of configuration variables to values. If arguments areprovided, they should be strings, and the return value will be a sequence givingthe associated values. If a given name does not have a corresponding value,None will be included for that variable.
Return the full path name of the configuration header. For Unix, this will bethe header generated by theconfigure script; for other platforms theheader will have been supplied directly by the Python source distribution. Thefile is a platform-specific text file.
Return the full path name of theMakefile used to build Python. ForUnix, this will be a file generated by theconfigure script; themeaning for other platforms will vary. The file is a platform-specific textfile, if it exists. This function is only useful on POSIX platforms.
Return the directory for either the general or platform-dependent C includefiles. Ifplat_specific is true, the platform-dependent include directory isreturned; if false or omitted, the platform-independent directory is returned.Ifprefix is given, it is used as either the prefix instead ofPREFIX, or as the exec-prefix instead ofEXEC_PREFIX ifplat_specific is true.
Return the directory for either the general or platform-dependent libraryinstallation. Ifplat_specific is true, the platform-dependent includedirectory is returned; if false or omitted, the platform-independent directoryis returned. Ifprefix is given, it is used as either the prefix instead ofPREFIX, or as the exec-prefix instead ofEXEC_PREFIX ifplat_specific is true. Ifstandard_lib is true, the directory for thestandard library is returned rather than the directory for the installation ofthird-party extensions.
The following function is only intended for use within thedistutilspackage.
Do any platform-specific customization of adistutils.ccompiler.CCompiler instance.
This function is only needed on Unix at this time, but should be calledconsistently to support forward-compatibility. It inserts the information thatvaries across Unix flavors and is stored in Python’sMakefile. Thisinformation includes the selected compiler, compiler and linker options, and theextension used by the linker for shared objects.
This function is even more special-purpose, and should only be used fromPython’s own build procedures.
Inform thedistutils.sysconfig module that it is being used as part ofthe build process for Python. This changes a lot of relative locations forfiles, allowing them to be located in the build area rather than in an installedPython.
distutils.text_file — The TextFile class¶This module provides theTextFile class, which gives an interface totext files that (optionally) takes care of stripping comments, ignoring blanklines, and joining lines with backslashes.
This class provides a file-like object that takes care of all the things youcommonly want to do when processing a text file that has some line-by-linesyntax: strip comments (as long as# is your comment character), skip blanklines, join adjacent lines by escaping the newline (ie. backslash at end ofline), strip leading and/or trailing whitespace. All of these are optional andindependently controllable.
The class provides awarn() method so you can generate warning messagesthat report physical line number, even if the logical line in question spansmultiple physical lines. Also providesunreadline() for implementingline-at-a-time lookahead.
TextFile instances are create with eitherfilename,file, or both.RuntimeError is raised if both areNone.filename should be astring, andfile a file object (or something that providesreadline()andclose() methods). It is recommended that you supply at leastfilename, so thatTextFile can include it in warning messages. Iffile is not supplied,TextFile creates its own using theopen() built-in function.
The options are all boolean, and affect the values returned byreadline()
option name | description | default |
|---|---|---|
strip_comments | strip from | true |
lstrip_ws | strip leading whitespace fromeach line before returning it | false |
rstrip_ws | strip trailing whitespace(including line terminator!)from each line beforereturning it. | true |
skip_blanks | skip lines that are empty*after* stripping commentsand whitespace. (If bothlstrip_ws and rstrip_ws arefalse, then some lines mayconsist of solely whitespace:these will *not* be skipped,even ifskip_blanks istrue.) | true |
join_lines | if a backslash is the lastnon-newline character on aline after stripping commentsand whitespace, join thefollowing line to it to formone logical line; if Nconsecutive lines end with abackslash, then N+1 physicallines will be joined to formone logical line. | false |
collapse_join | strip leading whitespace fromlines that are joined to theirpredecessor; only matters if | false |
Note that sincerstrip_ws can strip the trailing newline, the semantics ofreadline() must differ from those of the built-in file object’sreadline() method! In particular,readline() returnsNone forend-of-file: an empty string might just be a blank line (or an all-whitespaceline), ifrstrip_ws is true butskip_blanks is not.
Open a new filefilename. This overrides anyfile orfilenameconstructor arguments.
Close the current file and forget everything we know about it (including thefilename and the current line number).
Print (to stderr) a warning message tied to the current logical line in thecurrent file. If the current logical line in the file spans multiple physicallines, the warning refers to the whole range, such as"lines3-5". Ifline is supplied, it overrides the current line number; it may be a list ortuple to indicate a range of physical lines, or an integer for a singlephysical line.
Read and return a single logical line from the current file (or from an internalbuffer if lines have previously been “unread” withunreadline()). If thejoin_lines option is true, this may involve reading multiple physical linesconcatenated into a single string. Updates the current line number, so callingwarn() afterreadline() emits a warning about the physical line(s)just read. ReturnsNone on end-of-file, since the empty string can occurifrstrip_ws is true butstrip_blanks is not.
Read and return the list of all logical lines remaining in the current file.This updates the current line number to the last line of the file.
Pushline (a string) onto an internal buffer that will be checked by futurereadline() calls. Handy for implementing a parser with line-at-a-timelookahead. Note that lines that are “unread” withunreadline() are notsubsequently re-cleansed (whitespace stripped, or whatever) when read withreadline(). If multiple calls are made tounreadline() before a calltoreadline(), the lines will be returned most in most recent first order.
distutils.version — Version number classes¶distutils.cmd — Abstract base class for Distutils commands¶This module supplies the abstract base classCommand.
Abstract base class for defining command classes, the “worker bees” of theDistutils. A useful analogy for command classes is to think of them assubroutines with local variables calledoptions. The options are declaredininitialize_options() and defined (given their final values) infinalize_options(), both of which must be defined by every commandclass. The distinction between the two is necessary because option valuesmight come from the outside world (command line, config file, …), and anyoptions dependent on other options must be computed after these outsideinfluences have been processed — hencefinalize_options(). The bodyof the subroutine, where it does all its work based on the values of itsoptions, is therun() method, which must also be implemented by everycommand class.
The class constructor takes a single argumentdist, aDistribution instance.
This section outlines the steps to create a new Distutils command.
A new command lives in a module in thedistutils.command package. Thereis a sample template in that directory calledcommand_template. Copythis file to a new module with the same name as the new command you’reimplementing. This module should implement a class with the same name as themodule (and the command). So, for instance, to create the commandpeel_banana (so that users can runsetup.pypeel_banana), you’d copycommand_template todistutils/command/peel_banana.py, then editit so that it’s implementing the classpeel_banana, a subclass ofdistutils.cmd.Command.
Subclasses ofCommand must define the following methods.
Set default values for all the options that this command supports. Note thatthese defaults may be overridden by other commands, by the setup script, byconfig files, or by the command-line. Thus, this is not the place to codedependencies between options; generally,initialize_options()implementations are just a bunch ofself.foo=None assignments.
Set final values for all the options that this command supports. This isalways called as late as possible, ie. after any option assignments from thecommand-line or from other commands have been done. Thus, this is the placeto code option dependencies: iffoo depends onbar, then it is safe tosetfoo frombar as long asfoo still has the same value it wasassigned ininitialize_options().
A command’s raison d’etre: carry out the action it exists to perform, controlledby the options initialized ininitialize_options(), customized by othercommands, the setup script, the command-line, and config files, and finalized infinalize_options(). All terminal output and filesystem interaction shouldbe done byrun().
sub_commands formalizes the notion of a “family” of commands,e.g.install as the parent with sub-commandsinstall_lib,install_headers, etc. The parent of a family of commands definessub_commands as a class attribute; it’s a list of 2-tuples(command_name,predicate), withcommand_name a string andpredicate a function, astring orNone.predicate is a method of the parent command thatdetermines whether the corresponding command is applicable in the currentsituation. (E.g.install_headers is only applicable if we have any Cheader files to install.) Ifpredicate isNone, that command is alwaysapplicable.
sub_commands is usually defined at theend of a class, becausepredicates can be methods of the class, so they must already have beendefined. The canonical example is theinstall command.
distutils.command — Individual Distutils commands¶distutils.command.bdist — Build a binary installer¶distutils.command.bdist_packager — Abstract base class for packagers¶distutils.command.bdist_dumb — Build a “dumb” installer¶distutils.command.bdist_rpm — Build a binary distribution as a Redhat RPM and SRPM¶distutils.command.sdist — Build a source distribution¶distutils.command.build — Build all files of a package¶distutils.command.build_clib — Build any C libraries in a package¶distutils.command.build_ext — Build any extensions in a package¶distutils.command.build_py — Build the .py/.pyc files of a package¶distutils.command.build_scripts — Build the scripts of a package¶distutils.command.clean — Clean a package build area¶This command removes the temporary files created bybuildand its subcommands, like intermediary compiled object files. Withthe--all option, the complete build directory will be removed.
Extension modules builtin placewill not be cleaned, as they are not in the build directory.
distutils.command.config — Perform package configuration¶distutils.command.install — Install a package¶distutils.command.install_data — Install data files from a package¶distutils.command.install_headers — Install C/C++ header files from a package¶distutils.command.install_lib — Install library files from a package¶distutils.command.install_scripts — Install script files from a package¶distutils.command.register — Register a module with the Python Package Index¶Theregister command registers the package with the Python Package Index.This is described in more detail inPEP 301.
distutils.command.check — Check the meta-data of a package¶Thecheck command performs some tests on the meta-data of a package.For example, it verifies that all required meta-data are provided asthe arguments passed to thesetup() function.
distutils.core — Core Distutils functionalitydistutils.ccompiler — CCompiler base classgen_lib_options()gen_preprocess_options()get_default_compiler()new_compiler()show_compilers()CCompilerCCompiler.add_include_dir()CCompiler.set_include_dirs()CCompiler.add_library()CCompiler.set_libraries()CCompiler.add_library_dir()CCompiler.set_library_dirs()CCompiler.add_runtime_library_dir()CCompiler.set_runtime_library_dirs()CCompiler.define_macro()CCompiler.undefine_macro()CCompiler.add_link_object()CCompiler.set_link_objects()CCompiler.detect_language()CCompiler.find_library_file()CCompiler.has_function()CCompiler.library_dir_option()CCompiler.library_option()CCompiler.runtime_library_dir_option()CCompiler.set_executables()CCompiler.compile()CCompiler.create_static_lib()CCompiler.link()CCompiler.link_executable()CCompiler.link_shared_lib()CCompiler.link_shared_object()CCompiler.preprocess()CCompiler.executable_filename()CCompiler.library_filename()CCompiler.object_filenames()CCompiler.shared_object_filename()CCompiler.execute()CCompiler.spawn()CCompiler.mkpath()CCompiler.move_file()CCompiler.announce()CCompiler.warn()CCompiler.debug_print()distutils.unixccompiler — Unix C Compilerdistutils.msvccompiler — Microsoft Compilerdistutils.bcppcompiler — Borland Compilerdistutils.cygwinccompiler — Cygwin Compilerdistutils.archive_util — Archiving utilitiesdistutils.dep_util — Dependency checkingdistutils.dir_util — Directory tree operationsdistutils.file_util — Single file operationsdistutils.util — Miscellaneous other utility functionsdistutils.dist — The Distribution classdistutils.extension — The Extension classdistutils.debug — Distutils debug modedistutils.errors — Distutils exceptionsdistutils.fancy_getopt — Wrapper around the standard getopt moduledistutils.filelist — The FileList classdistutils.log — SimplePEP 282-style loggingdistutils.spawn — Spawn a sub-processdistutils.sysconfig — System configuration informationdistutils.text_file — The TextFile classdistutils.version — Version number classesdistutils.cmd — Abstract base class for Distutils commandsdistutils.command — Individual Distutils commandsdistutils.command.bdist — Build a binary installerdistutils.command.bdist_packager — Abstract base class for packagersdistutils.command.bdist_dumb — Build a “dumb” installerdistutils.command.bdist_rpm — Build a binary distribution as a Redhat RPM and SRPMdistutils.command.sdist — Build a source distributiondistutils.command.build — Build all files of a packagedistutils.command.build_clib — Build any C libraries in a packagedistutils.command.build_ext — Build any extensions in a packagedistutils.command.build_py — Build the .py/.pyc files of a packagedistutils.command.build_scripts — Build the scripts of a packagedistutils.command.clean — Clean a package build areadistutils.command.config — Perform package configurationdistutils.command.install — Install a packagedistutils.command.install_data — Install data files from a packagedistutils.command.install_headers — Install C/C++ header files from a packagedistutils.command.install_lib — Install library files from a packagedistutils.command.install_scripts — Install script files from a packagedistutils.command.register — Register a module with the Python Package Indexdistutils.command.check — Check the meta-data of a package