├── .gitignore ├── ACKS.txt ├── Makefile ├── README ├── README.txt ├── about.rst ├── bugs.rst ├── conf.py ├── contents.rst ├── copyright.rst ├── data └── refcounts.dat ├── distutils ├── apiref.rst ├── builtdist.rst ├── commandref.rst ├── configfile.rst ├── examples.rst ├── extending.rst ├── index.rst ├── introduction.rst ├── packageindex.rst ├── setupscript.rst ├── sourcedist.rst └── uploading.rst ├── documenting ├── building.rst ├── fromlatex.rst ├── index.rst ├── intro.rst ├── markup.rst ├── rest.rst └── style.rst ├── extending ├── building.rst ├── embedding.rst ├── extending.rst ├── index.rst ├── newtypes.rst └── windows.rst ├── faq ├── design.rst ├── extending.rst ├── general.rst ├── gui.rst ├── index.rst ├── installed.rst ├── library.rst ├── programming.rst ├── python-video-icon.png └── windows.rst ├── glossary.rst ├── howto ├── advocacy.rst ├── cporting.rst ├── curses.rst ├── descriptor.rst ├── doanddont.rst ├── functional.rst ├── index.rst ├── logging-cookbook.rst ├── logging.rst ├── regex.rst ├── sockets.rst ├── sorting.rst ├── unicode.rst ├── urllib2.rst └── webservers.rst ├── includes ├── email-alternative.py ├── email-dir.py ├── email-headers.py ├── email-mime.py ├── email-simple.py ├── email-unpack.py ├── minidom-example.py ├── mp_benchmarks.py ├── mp_newtype.py ├── mp_pool.py ├── mp_synchronize.py ├── mp_webserver.py ├── mp_workers.py ├── noddy.c ├── noddy2.c ├── noddy3.c ├── noddy4.c ├── run-func.c ├── setup.py ├── shoddy.c ├── sqlite3 │ ├── adapter_datetime.py │ ├── adapter_point_1.py │ ├── adapter_point_2.py │ ├── collation_reverse.py │ ├── complete_statement.py │ ├── connect_db_1.py │ ├── connect_db_2.py │ ├── converter_point.py │ ├── countcursors.py │ ├── createdb.py │ ├── ctx_manager.py │ ├── execsql_fetchonerow.py │ ├── execsql_printall_1.py │ ├── execute_1.py │ ├── execute_2.py │ ├── execute_3.py │ ├── executemany_1.py │ ├── executemany_2.py │ ├── executescript.py │ ├── insert_more_people.py │ ├── load_extension.py │ ├── md5func.py │ ├── mysumaggr.py │ ├── parse_colnames.py │ ├── pysqlite_datetime.py │ ├── row_factory.py │ ├── rowclass.py │ ├── shared_cache.py │ ├── shortcut_methods.py │ ├── simple_tableprinter.py │ └── text_factory.py ├── test.py ├── typestruct.h └── tzinfo-examples.py ├── install └── index.rst ├── library ├── 2to3.rst ├── __builtin__.rst ├── __future__.rst ├── __main__.rst ├── _winreg.rst ├── abc.rst ├── aepack.rst ├── aetools.rst ├── aetypes.rst ├── aifc.rst ├── al.rst ├── allos.rst ├── anydbm.rst ├── archiving.rst ├── argparse.rst ├── array.rst ├── ast.rst ├── asynchat.rst ├── asyncore.rst ├── atexit.rst ├── audioop.rst ├── autogil.rst ├── base64.rst ├── basehttpserver.rst ├── bastion.rst ├── bdb.rst ├── binascii.rst ├── binhex.rst ├── bisect.rst ├── bsddb.rst ├── bz2.rst ├── calendar.rst ├── carbon.rst ├── cd.rst ├── cgi.rst ├── cgihttpserver.rst ├── cgitb.rst ├── chunk.rst ├── cmath.rst ├── cmd.rst ├── code.rst ├── codecs.rst ├── codeop.rst ├── collections.rst ├── colorpicker.rst ├── colorsys.rst ├── commands.rst ├── compileall.rst ├── compiler.rst ├── configparser.rst ├── constants.rst ├── contextlib.rst ├── cookie.rst ├── cookielib.rst ├── copy.rst ├── copy_reg.rst ├── crypt.rst ├── crypto.rst ├── csv.rst ├── ctypes.rst ├── curses.ascii.rst ├── curses.panel.rst ├── curses.rst ├── custominterp.rst ├── datatypes.rst ├── datetime.rst ├── dbhash.rst ├── dbm.rst ├── debug.rst ├── decimal.rst ├── development.rst ├── difflib.rst ├── dircache.rst ├── dis.rst ├── distutils.rst ├── dl.rst ├── doctest.rst ├── docxmlrpcserver.rst ├── dumbdbm.rst ├── dummy_thread.rst ├── dummy_threading.rst ├── easydialogs.rst ├── email-examples.rst ├── email.charset.rst ├── email.encoders.rst ├── email.errors.rst ├── email.generator.rst ├── email.header.rst ├── email.iterators.rst ├── email.message.rst ├── email.mime.rst ├── email.parser.rst ├── email.rst ├── email.util.rst ├── errno.rst ├── exceptions.rst ├── fcntl.rst ├── filecmp.rst ├── fileformats.rst ├── fileinput.rst ├── filesys.rst ├── fl.rst ├── fm.rst ├── fnmatch.rst ├── formatter.rst ├── fpectl.rst ├── fpformat.rst ├── fractions.rst ├── framework.rst ├── frameworks.rst ├── ftplib.rst ├── functions.rst ├── functools.rst ├── future_builtins.rst ├── gc.rst ├── gdbm.rst ├── gensuitemodule.rst ├── getopt.rst ├── getpass.rst ├── gettext.rst ├── gl.rst ├── glob.rst ├── grp.rst ├── gzip.rst ├── hashlib.rst ├── heapq.rst ├── hmac.rst ├── hotshot.rst ├── htmllib.rst ├── htmlparser.rst ├── httplib.rst ├── i18n.rst ├── ic.rst ├── idle.rst ├── imageop.rst ├── imaplib.rst ├── imgfile.rst ├── imghdr.rst ├── imp.rst ├── importlib.rst ├── imputil.rst ├── index.rst ├── inspect.rst ├── internet.rst ├── intro.rst ├── io.rst ├── ipc.rst ├── itertools.rst ├── jpeg.rst ├── json.rst ├── keyword.rst ├── language.rst ├── linecache.rst ├── locale.rst ├── logging.config.rst ├── logging.handlers.rst ├── logging.rst ├── mac.rst ├── macos.rst ├── macosa.rst ├── macostools.rst ├── macpath.rst ├── mailbox.rst ├── mailcap.rst ├── markup.rst ├── marshal.rst ├── math.rst ├── md5.rst ├── mhlib.rst ├── mimetools.rst ├── mimetypes.rst ├── mimewriter.rst ├── mimify.rst ├── miniaeframe.rst ├── misc.rst ├── mm.rst ├── mmap.rst ├── modulefinder.rst ├── modules.rst ├── msilib.rst ├── msvcrt.rst ├── multifile.rst ├── multiprocessing.rst ├── mutex.rst ├── netdata.rst ├── netrc.rst ├── new.rst ├── nis.rst ├── nntplib.rst ├── numbers.rst ├── numeric.rst ├── operator.rst ├── optparse.rst ├── os.path.rst ├── os.rst ├── ossaudiodev.rst ├── othergui.rst ├── parser.rst ├── pdb.rst ├── persistence.rst ├── pickle.rst ├── pickletools.rst ├── pipes.rst ├── pkgutil.rst ├── platform.rst ├── plistlib.rst ├── popen2.rst ├── poplib.rst ├── posix.rst ├── posixfile.rst ├── pprint.rst ├── profile.rst ├── pty.rst ├── pwd.rst ├── py_compile.rst ├── pyclbr.rst ├── pydoc.rst ├── pyexpat.rst ├── python.rst ├── queue.rst ├── quopri.rst ├── random.rst ├── re.rst ├── readline.rst ├── repr.rst ├── resource.rst ├── restricted.rst ├── rexec.rst ├── rfc822.rst ├── rlcompleter.rst ├── robotparser.rst ├── runpy.rst ├── sched.rst ├── scrolledtext.rst ├── select.rst ├── sets.rst ├── sgi.rst ├── sgmllib.rst ├── sha.rst ├── shelve.rst ├── shlex.rst ├── shutil.rst ├── signal.rst ├── simplehttpserver.rst ├── simplexmlrpcserver.rst ├── site.rst ├── smtpd.rst ├── smtplib.rst ├── sndhdr.rst ├── socket.rst ├── socketserver.rst ├── someos.rst ├── spwd.rst ├── sqlite3.rst ├── ssl.rst ├── stat.rst ├── statvfs.rst ├── stdtypes.rst ├── string.rst ├── stringio.rst ├── stringprep.rst ├── strings.rst ├── struct.rst ├── subprocess.rst ├── sun.rst ├── sunau.rst ├── sunaudio.rst ├── symbol.rst ├── symtable.rst ├── sys.rst ├── sysconfig.rst ├── syslog.rst ├── tabnanny.rst ├── tarfile.rst ├── telnetlib.rst ├── tempfile.rst ├── termios.rst ├── test.rst ├── textwrap.rst ├── thread.rst ├── threading.rst ├── time.rst ├── timeit.rst ├── tix.rst ├── tk.rst ├── tkinter.rst ├── token.rst ├── tokenize.rst ├── trace.rst ├── traceback.rst ├── ttk.rst ├── tty.rst ├── turtle.rst ├── types.rst ├── undoc.rst ├── unicodedata.rst ├── unittest.rst ├── unix.rst ├── urllib.rst ├── urllib2.rst ├── urlparse.rst ├── user.rst ├── userdict.rst ├── uu.rst ├── uuid.rst ├── warnings.rst ├── wave.rst ├── weakref.rst ├── webbrowser.rst ├── whichdb.rst ├── windows.rst ├── winsound.rst ├── wsgiref.rst ├── xdrlib.rst ├── xml.dom.minidom.rst ├── xml.dom.pulldom.rst ├── xml.dom.rst ├── xml.etree.elementtree.rst ├── xml.sax.handler.rst ├── xml.sax.reader.rst ├── xml.sax.rst ├── xml.sax.utils.rst ├── xmllib.rst ├── xmlrpclib.rst ├── zipfile.rst ├── zipimport.rst └── zlib.rst ├── license.rst ├── make.bat ├── net-api ├── extending.rst ├── index.rst └── parsing.rst ├── reference ├── compound_stmts.rst ├── datamodel.rst ├── executionmodel.rst ├── expressions.rst ├── grammar.rst ├── index.rst ├── introduction.rst ├── lexical_analysis.rst ├── simple_stmts.rst └── toplevel_components.rst ├── tools ├── dailybuild.py ├── roman.py ├── rstlint.py ├── sphinx-build.py └── sphinxext │ ├── download.html │ ├── indexcontent.html │ ├── indexsidebar.html │ ├── layout.html │ ├── opensearch.xml │ ├── patchlevel.py │ ├── pyspecific.py │ ├── static │ ├── basic.css │ └── py.png │ ├── susp-ignored.csv │ └── suspicious.py ├── tutorial ├── appetite.rst ├── classes.rst ├── controlflow.rst ├── datastructures.rst ├── errors.rst ├── floatingpoint.rst ├── index.rst ├── inputoutput.rst ├── interactive.rst ├── interpreter.rst ├── introduction.rst ├── modules.rst ├── stdlib.rst ├── stdlib2.rst └── whatnow.rst ├── using ├── cmdline.rst ├── index.rst ├── mac.rst ├── unix.rst └── windows.rst └── whatsnew ├── 2.0.rst ├── 2.1.rst ├── 2.2.rst ├── 2.3.rst ├── 2.4.rst ├── 2.5.rst ├── 2.6.rst ├── 2.7.rst └── index.rst /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | build -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | IronPython Documentation - contains the IronPython version of the standard Python documentation. 2 | -------------------------------------------------------------------------------- /about.rst: -------------------------------------------------------------------------------- 1 | ===================== 2 | About these documents 3 | ===================== 4 | 5 | 6 | These documents are generated from `reStructuredText`_ sources by `Sphinx`_, a 7 | document processor specifically written for the Python documentation. 8 | 9 | .. _reStructuredText: http://docutils.sf.net/rst.html 10 | .. _Sphinx: http://sphinx.pocoo.org/ 11 | 12 | .. In the online version of these documents, you can submit comments and suggest 13 | changes directly on the documentation pages. 14 | 15 | Development of the documentation and its toolchain takes place on the 16 | docs@python.org mailing list. We're always looking for volunteers wanting 17 | to help with the docs, so feel free to send a mail there! 18 | 19 | Many thanks go to: 20 | 21 | * Fred L. Drake, Jr., the creator of the original Python documentation toolset 22 | and writer of much of the content; 23 | * the `Docutils `_ project for creating 24 | reStructuredText and the Docutils suite; 25 | * Fredrik Lundh for his `Alternative Python Reference 26 | `_ project from which Sphinx got many good 27 | ideas. 28 | 29 | See :ref:`reporting-bugs` for information how to report bugs in this 30 | documentation, or Python itself. 31 | 32 | .. including the ACKS file here so that it can be maintained separately 33 | .. include:: ACKS.txt 34 | 35 | It is only with the input and contributions of the Python community 36 | that Python has such wonderful documentation -- Thank You! 37 | -------------------------------------------------------------------------------- /contents.rst: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | IronPython Documentation contents 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | 5 | .. toctree:: 6 | 7 | whatsnew/index.rst 8 | tutorial/index.rst 9 | using/index.rst 10 | reference/index.rst 11 | library/index.rst 12 | extending/index.rst 13 | net-api/index.rst 14 | distutils/index.rst 15 | install/index.rst 16 | documenting/index.rst 17 | howto/index.rst 18 | faq/index.rst 19 | glossary.rst 20 | 21 | about.rst 22 | bugs.rst 23 | copyright.rst 24 | license.rst 25 | -------------------------------------------------------------------------------- /copyright.rst: -------------------------------------------------------------------------------- 1 | ********* 2 | Copyright 3 | ********* 4 | 5 | IronPython and parts of this documentation is: 6 | 7 | Copyright © 2006-2010 Microsoft. All rights reserved. 8 | 9 | Copyright © 2010-2012 IronPython Contributors. 10 | 11 | Python and this documentation is: 12 | 13 | Copyright © 2001-2010 Python Software Foundation. All rights reserved. 14 | 15 | Copyright © 2000 BeOpen.com. All rights reserved. 16 | 17 | Copyright © 1995-2000 Corporation for National Research Initiatives. All rights 18 | reserved. 19 | 20 | Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. 21 | 22 | ------- 23 | 24 | See :ref:`history-and-license` for complete license and permissions information. 25 | 26 | -------------------------------------------------------------------------------- /distutils/commandref.rst: -------------------------------------------------------------------------------- 1 | .. _reference: 2 | 3 | ***************** 4 | Command Reference 5 | ***************** 6 | 7 | .. % \section{Building modules: the \protect\command{build} command family} 8 | .. % \label{build-cmds} 9 | .. % \subsubsection{\protect\command{build}} 10 | .. % \label{build-cmd} 11 | .. % \subsubsection{\protect\command{build\_py}} 12 | .. % \label{build-py-cmd} 13 | .. % \subsubsection{\protect\command{build\_ext}} 14 | .. % \label{build-ext-cmd} 15 | .. % \subsubsection{\protect\command{build\_clib}} 16 | .. % \label{build-clib-cmd} 17 | 18 | 19 | .. _install-cmd: 20 | 21 | Installing modules: the :command:`install` command family 22 | ========================================================= 23 | 24 | The install command ensures that the build commands have been run and then runs 25 | the subcommands :command:`install_lib`, :command:`install_data` and 26 | :command:`install_scripts`. 27 | 28 | .. % \subsubsection{\protect\command{install\_lib}} 29 | .. % \label{install-lib-cmd} 30 | 31 | 32 | .. _install-data-cmd: 33 | 34 | :command:`install_data` 35 | ----------------------- 36 | 37 | This command installs all data files provided with the distribution. 38 | 39 | 40 | .. _install-scripts-cmd: 41 | 42 | :command:`install_scripts` 43 | -------------------------- 44 | 45 | This command installs all (Python) scripts in the distribution. 46 | 47 | .. % \subsection{Cleaning up: the \protect\command{clean} command} 48 | .. % \label{clean-cmd} 49 | 50 | 51 | .. % \section{Creating a built distribution: the 52 | .. % \protect\command{bdist} command family} 53 | .. % \label{bdist-cmds} 54 | 55 | .. % \subsection{\protect\command{bdist}} 56 | .. % \subsection{\protect\command{bdist\_dumb}} 57 | .. % \subsection{\protect\command{bdist\_rpm}} 58 | .. % \subsection{\protect\command{bdist\_wininst}} 59 | 60 | 61 | -------------------------------------------------------------------------------- /distutils/index.rst: -------------------------------------------------------------------------------- 1 | .. _distutils-index: 2 | 3 | ############################### 4 | Distributing Python Modules 5 | ############################### 6 | 7 | :Authors: Greg Ward, Anthony Baxter 8 | :Email: distutils-sig@python.org 9 | :Release: |version| 10 | :Date: |today| 11 | 12 | This document describes the Python Distribution Utilities ("Distutils") from 13 | the module developer's point of view, describing how to use the Distutils to 14 | make Python modules and extensions easily available to a wider audience with 15 | very little overhead for build/release/install mechanics. 16 | 17 | .. toctree:: 18 | :maxdepth: 2 19 | :numbered: 20 | 21 | introduction.rst 22 | setupscript.rst 23 | configfile.rst 24 | sourcedist.rst 25 | builtdist.rst 26 | packageindex.rst 27 | uploading.rst 28 | examples.rst 29 | extending.rst 30 | commandref.rst 31 | apiref.rst 32 | -------------------------------------------------------------------------------- /documenting/index.rst: -------------------------------------------------------------------------------- 1 | .. _documenting-index: 2 | 3 | ###################### 4 | Documenting Python 5 | ###################### 6 | 7 | 8 | The Python language has a substantial body of documentation, much of it 9 | contributed by various authors. The markup used for the Python documentation is 10 | `reStructuredText`_, developed by the `docutils`_ project, amended by custom 11 | directives and using a toolset named `Sphinx`_ to postprocess the HTML output. 12 | 13 | This document describes the style guide for our documentation as well as the 14 | custom reStructuredText markup introduced by Sphinx to support Python 15 | documentation and how it should be used. 16 | 17 | .. _reStructuredText: http://docutils.sf.net/rst.html 18 | .. _docutils: http://docutils.sf.net/ 19 | .. _Sphinx: http://sphinx.pocoo.org/ 20 | 21 | .. note:: 22 | 23 | If you're interested in contributing to Python's documentation, there's no 24 | need to write reStructuredText if you're not so inclined; plain text 25 | contributions are more than welcome as well. Send an e-mail to 26 | docs@python.org or open an issue on the :ref:`tracker `. 27 | 28 | 29 | .. toctree:: 30 | :numbered: 31 | :maxdepth: 1 32 | 33 | intro.rst 34 | style.rst 35 | rest.rst 36 | markup.rst 37 | fromlatex.rst 38 | building.rst 39 | -------------------------------------------------------------------------------- /documenting/intro.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | Python's documentation has long been considered to be good for a free 5 | programming language. There are a number of reasons for this, the most 6 | important being the early commitment of Python's creator, Guido van Rossum, to 7 | providing documentation on the language and its libraries, and the continuing 8 | involvement of the user community in providing assistance for creating and 9 | maintaining documentation. 10 | 11 | The involvement of the community takes many forms, from authoring to bug reports 12 | to just plain complaining when the documentation could be more complete or 13 | easier to use. 14 | 15 | This document is aimed at authors and potential authors of documentation for 16 | Python. More specifically, it is for people contributing to the standard 17 | documentation and developing additional documents using the same tools as the 18 | standard documents. This guide will be less useful for authors using the Python 19 | documentation tools for topics other than Python, and less useful still for 20 | authors not using the tools at all. 21 | 22 | If your interest is in contributing to the Python documentation, but you don't 23 | have the time or inclination to learn reStructuredText and the markup structures 24 | documented here, there's a welcoming place for you among the Python contributors 25 | as well. Any time you feel that you can clarify existing documentation or 26 | provide documentation that's missing, the existing documentation team will 27 | gladly work with you to integrate your text, dealing with the markup for you. 28 | Please don't let the material in this document stand between the documentation 29 | and your desire to help out! -------------------------------------------------------------------------------- /extending/index.rst: -------------------------------------------------------------------------------- 1 | .. _extending-index: 2 | 3 | ################################################## 4 | Extending and Embedding the Python Interpreter 5 | ################################################## 6 | 7 | :Release: |version| 8 | :Date: |today| 9 | 10 | This document describes how to write modules in C or C++ to extend the Python 11 | interpreter with new modules. Those modules can define new functions but also 12 | new object types and their methods. The document also describes how to embed 13 | the Python interpreter in another application, for use as an extension language. 14 | Finally, it shows how to compile and link extension modules so that they can be 15 | loaded dynamically (at run time) into the interpreter, if the underlying 16 | operating system supports this feature. 17 | 18 | This document assumes basic knowledge about Python. For an informal 19 | introduction to the language, see :ref:`tutorial-index`. :ref:`reference-index` 20 | gives a more formal definition of the language. :ref:`library-index` documents 21 | the existing object types, functions and modules (both built-in and written in 22 | Python) that give the language its wide application range. 23 | 24 | For a detailed description of the whole Python/C API, see the separate 25 | :ref:`c-api-index`. 26 | 27 | .. toctree:: 28 | :maxdepth: 2 29 | :numbered: 30 | 31 | extending.rst 32 | newtypes.rst 33 | building.rst 34 | windows.rst 35 | embedding.rst 36 | -------------------------------------------------------------------------------- /faq/index.rst: -------------------------------------------------------------------------------- 1 | ################################### 2 | Python Frequently Asked Questions 3 | ################################### 4 | 5 | :Release: |version| 6 | :Date: |today| 7 | 8 | .. toctree:: 9 | :maxdepth: 1 10 | 11 | general.rst 12 | programming.rst 13 | design.rst 14 | library.rst 15 | extending.rst 16 | windows.rst 17 | gui.rst 18 | installed.rst 19 | -------------------------------------------------------------------------------- /faq/installed.rst: -------------------------------------------------------------------------------- 1 | ============================================= 2 | "Why is Python Installed on my Computer?" FAQ 3 | ============================================= 4 | 5 | What is Python? 6 | --------------- 7 | 8 | Python is a programming language. It's used for many different applications. 9 | It's used in some high schools and colleges as an introductory programming 10 | language because Python is easy to learn, but it's also used by professional 11 | software developers at places such as Google, NASA, and Lucasfilm Ltd. 12 | 13 | If you wish to learn more about Python, start with the `Beginner's Guide to 14 | Python `_. 15 | 16 | 17 | Why is Python installed on my machine? 18 | -------------------------------------- 19 | 20 | If you find Python installed on your system but don't remember installing it, 21 | there are several possible ways it could have gotten there. 22 | 23 | * Perhaps another user on the computer wanted to learn programming and installed 24 | it; you'll have to figure out who's been using the machine and might have 25 | installed it. 26 | * A third-party application installed on the machine might have been written in 27 | Python and included a Python installation. For a home computer, the most 28 | common such application is `PySol `_, a 29 | solitaire game that includes over 1000 different games and variations. 30 | * Some Windows machines also have Python installed. At this writing we're aware 31 | of computers from Hewlett-Packard and Compaq that include Python. Apparently 32 | some of HP/Compaq's administrative tools are written in Python. 33 | * All Apple computers running Mac OS X have Python installed; it's included in 34 | the base installation. 35 | 36 | 37 | Can I delete Python? 38 | -------------------- 39 | 40 | That depends on where Python came from. 41 | 42 | If someone installed it deliberately, you can remove it without hurting 43 | anything. On Windows, use the Add/Remove Programs icon in the Control Panel. 44 | 45 | If Python was installed by a third-party application, you can also remove it, 46 | but that application will no longer work. You should use that application's 47 | uninstaller rather than removing Python directly. 48 | 49 | If Python came with your operating system, removing it is not recommended. If 50 | you remove it, whatever tools were written in Python will no longer run, and 51 | some of them might be important to you. Reinstalling the whole system would 52 | then be required to fix things again. 53 | 54 | -------------------------------------------------------------------------------- /faq/python-video-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IronLanguages/ironpython-docs/5e7a892ad46ae374bf85af45c093ad1ecb49fbbb/faq/python-video-icon.png -------------------------------------------------------------------------------- /howto/index.rst: -------------------------------------------------------------------------------- 1 | *************** 2 | Python HOWTOs 3 | *************** 4 | 5 | Python HOWTOs are documents that cover a single, specific topic, 6 | and attempt to cover it fairly completely. Modelled on the Linux 7 | Documentation Project's HOWTO collection, this collection is an 8 | effort to foster documentation that's more detailed than the 9 | Python Library Reference. 10 | 11 | Currently, the HOWTOs are: 12 | 13 | .. toctree:: 14 | :maxdepth: 1 15 | 16 | advocacy.rst 17 | cporting.rst 18 | curses.rst 19 | descriptor.rst 20 | doanddont.rst 21 | functional.rst 22 | logging.rst 23 | logging-cookbook.rst 24 | regex.rst 25 | sockets.rst 26 | sorting.rst 27 | unicode.rst 28 | urllib2.rst 29 | webservers.rst 30 | 31 | -------------------------------------------------------------------------------- /includes/email-alternative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import smtplib 4 | 5 | from email.mime.multipart import MIMEMultipart 6 | from email.mime.text import MIMEText 7 | 8 | # me == my email address 9 | # you == recipient's email address 10 | me = "my@email.com" 11 | you = "your@email.com" 12 | 13 | # Create message container - the correct MIME type is multipart/alternative. 14 | msg = MIMEMultipart('alternative') 15 | msg['Subject'] = "Link" 16 | msg['From'] = me 17 | msg['To'] = you 18 | 19 | # Create the body of the message (a plain-text and an HTML version). 20 | text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" 21 | html = """\ 22 | 23 | 24 | 25 |

Hi!
26 | How are you?
27 | Here is the link you wanted. 28 |

29 | 30 | 31 | """ 32 | 33 | # Record the MIME types of both parts - text/plain and text/html. 34 | part1 = MIMEText(text, 'plain') 35 | part2 = MIMEText(html, 'html') 36 | 37 | # Attach parts into message container. 38 | # According to RFC 2046, the last part of a multipart message, in this case 39 | # the HTML message, is best and preferred. 40 | msg.attach(part1) 41 | msg.attach(part2) 42 | 43 | # Send the message via local SMTP server. 44 | s = smtplib.SMTP('localhost') 45 | # sendmail function takes 3 arguments: sender's address, recipient's address 46 | # and message to send - here it is sent as one string. 47 | s.sendmail(me, you, msg.as_string()) 48 | s.quit() 49 | -------------------------------------------------------------------------------- /includes/email-headers.py: -------------------------------------------------------------------------------- 1 | # Import the email modules we'll need 2 | from email.parser import Parser 3 | 4 | # If the e-mail headers are in a file, uncomment this line: 5 | #headers = Parser().parse(open(messagefile, 'r')) 6 | 7 | # Or for parsing headers in a string, use: 8 | headers = Parser().parsestr('From: \n' 9 | 'To: \n' 10 | 'Subject: Test message\n' 11 | '\n' 12 | 'Body would go here\n') 13 | 14 | # Now the header items can be accessed as a dictionary: 15 | print 'To: %s' % headers['to'] 16 | print 'From: %s' % headers['from'] 17 | print 'Subject: %s' % headers['subject'] 18 | -------------------------------------------------------------------------------- /includes/email-mime.py: -------------------------------------------------------------------------------- 1 | # Import smtplib for the actual sending function 2 | import smtplib 3 | 4 | # Here are the email package modules we'll need 5 | from email.mime.image import MIMEImage 6 | from email.mime.multipart import MIMEMultipart 7 | 8 | COMMASPACE = ', ' 9 | 10 | # Create the container (outer) email message. 11 | msg = MIMEMultipart() 12 | msg['Subject'] = 'Our family reunion' 13 | # me == the sender's email address 14 | # family = the list of all recipients' email addresses 15 | msg['From'] = me 16 | msg['To'] = COMMASPACE.join(family) 17 | msg.preamble = 'Our family reunion' 18 | 19 | # Assume we know that the image files are all in PNG format 20 | for file in pngfiles: 21 | # Open the files in binary mode. Let the MIMEImage class automatically 22 | # guess the specific image type. 23 | fp = open(file, 'rb') 24 | img = MIMEImage(fp.read()) 25 | fp.close() 26 | msg.attach(img) 27 | 28 | # Send the email via our own SMTP server. 29 | s = smtplib.SMTP('localhost') 30 | s.sendmail(me, family, msg.as_string()) 31 | s.quit() 32 | -------------------------------------------------------------------------------- /includes/email-simple.py: -------------------------------------------------------------------------------- 1 | # Import smtplib for the actual sending function 2 | import smtplib 3 | 4 | # Import the email modules we'll need 5 | from email.mime.text import MIMEText 6 | 7 | # Open a plain text file for reading. For this example, assume that 8 | # the text file contains only ASCII characters. 9 | fp = open(textfile, 'rb') 10 | # Create a text/plain message 11 | msg = MIMEText(fp.read()) 12 | fp.close() 13 | 14 | # me == the sender's email address 15 | # you == the recipient's email address 16 | msg['Subject'] = 'The contents of %s' % textfile 17 | msg['From'] = me 18 | msg['To'] = you 19 | 20 | # Send the message via our own SMTP server, but don't include the 21 | # envelope header. 22 | s = smtplib.SMTP('localhost') 23 | s.sendmail(me, [you], msg.as_string()) 24 | s.quit() 25 | -------------------------------------------------------------------------------- /includes/email-unpack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """Unpack a MIME message into a directory of files.""" 4 | 5 | import os 6 | import sys 7 | import email 8 | import errno 9 | import mimetypes 10 | 11 | from optparse import OptionParser 12 | 13 | 14 | def main(): 15 | parser = OptionParser(usage="""\ 16 | Unpack a MIME message into a directory of files. 17 | 18 | Usage: %prog [options] msgfile 19 | """) 20 | parser.add_option('-d', '--directory', 21 | type='string', action='store', 22 | help="""Unpack the MIME message into the named 23 | directory, which will be created if it doesn't already 24 | exist.""") 25 | opts, args = parser.parse_args() 26 | if not opts.directory: 27 | parser.print_help() 28 | sys.exit(1) 29 | 30 | try: 31 | msgfile = args[0] 32 | except IndexError: 33 | parser.print_help() 34 | sys.exit(1) 35 | 36 | try: 37 | os.mkdir(opts.directory) 38 | except OSError, e: 39 | # Ignore directory exists error 40 | if e.errno != errno.EEXIST: 41 | raise 42 | 43 | fp = open(msgfile) 44 | msg = email.message_from_file(fp) 45 | fp.close() 46 | 47 | counter = 1 48 | for part in msg.walk(): 49 | # multipart/* are just containers 50 | if part.get_content_maintype() == 'multipart': 51 | continue 52 | # Applications should really sanitize the given filename so that an 53 | # email message can't be used to overwrite important files 54 | filename = part.get_filename() 55 | if not filename: 56 | ext = mimetypes.guess_extension(part.get_content_type()) 57 | if not ext: 58 | # Use a generic bag-of-bits extension 59 | ext = '.bin' 60 | filename = 'part-%03d%s' % (counter, ext) 61 | counter += 1 62 | fp = open(os.path.join(opts.directory, filename), 'wb') 63 | fp.write(part.get_payload(decode=True)) 64 | fp.close() 65 | 66 | 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /includes/minidom-example.py: -------------------------------------------------------------------------------- 1 | import xml.dom.minidom 2 | 3 | document = """\ 4 | 5 | Demo slideshow 6 | Slide title 7 | This is a demo 8 | Of a program for processing slides 9 | 10 | 11 | Another demo slide 12 | It is important 13 | To have more than 14 | one slide 15 | 16 | 17 | """ 18 | 19 | dom = xml.dom.minidom.parseString(document) 20 | 21 | def getText(nodelist): 22 | rc = [] 23 | for node in nodelist: 24 | if node.nodeType == node.TEXT_NODE: 25 | rc.append(node.data) 26 | return ''.join(rc) 27 | 28 | def handleSlideshow(slideshow): 29 | print "" 30 | handleSlideshowTitle(slideshow.getElementsByTagName("title")[0]) 31 | slides = slideshow.getElementsByTagName("slide") 32 | handleToc(slides) 33 | handleSlides(slides) 34 | print "" 35 | 36 | def handleSlides(slides): 37 | for slide in slides: 38 | handleSlide(slide) 39 | 40 | def handleSlide(slide): 41 | handleSlideTitle(slide.getElementsByTagName("title")[0]) 42 | handlePoints(slide.getElementsByTagName("point")) 43 | 44 | def handleSlideshowTitle(title): 45 | print "%s" % getText(title.childNodes) 46 | 47 | def handleSlideTitle(title): 48 | print "

%s

" % getText(title.childNodes) 49 | 50 | def handlePoints(points): 51 | print "
    " 52 | for point in points: 53 | handlePoint(point) 54 | print "
" 55 | 56 | def handlePoint(point): 57 | print "
  • %s
  • " % getText(point.childNodes) 58 | 59 | def handleToc(slides): 60 | for slide in slides: 61 | title = slide.getElementsByTagName("title")[0] 62 | print "

    %s

    " % getText(title.childNodes) 63 | 64 | handleSlideshow(dom) 65 | -------------------------------------------------------------------------------- /includes/mp_newtype.py: -------------------------------------------------------------------------------- 1 | # 2 | # This module shows how to use arbitrary callables with a subclass of 3 | # `BaseManager`. 4 | # 5 | # Copyright (c) 2006-2008, R Oudkerk 6 | # All rights reserved. 7 | # 8 | 9 | from multiprocessing import freeze_support 10 | from multiprocessing.managers import BaseManager, BaseProxy 11 | import operator 12 | 13 | ## 14 | 15 | class Foo(object): 16 | def f(self): 17 | print 'you called Foo.f()' 18 | def g(self): 19 | print 'you called Foo.g()' 20 | def _h(self): 21 | print 'you called Foo._h()' 22 | 23 | # A simple generator function 24 | def baz(): 25 | for i in xrange(10): 26 | yield i*i 27 | 28 | # Proxy type for generator objects 29 | class GeneratorProxy(BaseProxy): 30 | _exposed_ = ('next', '__next__') 31 | def __iter__(self): 32 | return self 33 | def next(self): 34 | return self._callmethod('next') 35 | def __next__(self): 36 | return self._callmethod('__next__') 37 | 38 | # Function to return the operator module 39 | def get_operator_module(): 40 | return operator 41 | 42 | ## 43 | 44 | class MyManager(BaseManager): 45 | pass 46 | 47 | # register the Foo class; make `f()` and `g()` accessible via proxy 48 | MyManager.register('Foo1', Foo) 49 | 50 | # register the Foo class; make `g()` and `_h()` accessible via proxy 51 | MyManager.register('Foo2', Foo, exposed=('g', '_h')) 52 | 53 | # register the generator function baz; use `GeneratorProxy` to make proxies 54 | MyManager.register('baz', baz, proxytype=GeneratorProxy) 55 | 56 | # register get_operator_module(); make public functions accessible via proxy 57 | MyManager.register('operator', get_operator_module) 58 | 59 | ## 60 | 61 | def test(): 62 | manager = MyManager() 63 | manager.start() 64 | 65 | print '-' * 20 66 | 67 | f1 = manager.Foo1() 68 | f1.f() 69 | f1.g() 70 | assert not hasattr(f1, '_h') 71 | assert sorted(f1._exposed_) == sorted(['f', 'g']) 72 | 73 | print '-' * 20 74 | 75 | f2 = manager.Foo2() 76 | f2.g() 77 | f2._h() 78 | assert not hasattr(f2, 'f') 79 | assert sorted(f2._exposed_) == sorted(['g', '_h']) 80 | 81 | print '-' * 20 82 | 83 | it = manager.baz() 84 | for i in it: 85 | print '<%d>' % i, 86 | print 87 | 88 | print '-' * 20 89 | 90 | op = manager.operator() 91 | print 'op.add(23, 45) =', op.add(23, 45) 92 | print 'op.pow(2, 94) =', op.pow(2, 94) 93 | print 'op.getslice(range(10), 2, 6) =', op.getslice(range(10), 2, 6) 94 | print 'op.repeat(range(5), 3) =', op.repeat(range(5), 3) 95 | print 'op._exposed_ =', op._exposed_ 96 | 97 | ## 98 | 99 | if __name__ == '__main__': 100 | freeze_support() 101 | test() 102 | -------------------------------------------------------------------------------- /includes/mp_webserver.py: -------------------------------------------------------------------------------- 1 | # 2 | # Example where a pool of http servers share a single listening socket 3 | # 4 | # On Windows this module depends on the ability to pickle a socket 5 | # object so that the worker processes can inherit a copy of the server 6 | # object. (We import `multiprocessing.reduction` to enable this pickling.) 7 | # 8 | # Not sure if we should synchronize access to `socket.accept()` method by 9 | # using a process-shared lock -- does not seem to be necessary. 10 | # 11 | # Copyright (c) 2006-2008, R Oudkerk 12 | # All rights reserved. 13 | # 14 | 15 | import os 16 | import sys 17 | 18 | from multiprocessing import Process, current_process, freeze_support 19 | from BaseHTTPServer import HTTPServer 20 | from SimpleHTTPServer import SimpleHTTPRequestHandler 21 | 22 | if sys.platform == 'win32': 23 | import multiprocessing.reduction # make sockets pickable/inheritable 24 | 25 | 26 | def note(format, *args): 27 | sys.stderr.write('[%s]\t%s\n' % (current_process().name, format%args)) 28 | 29 | 30 | class RequestHandler(SimpleHTTPRequestHandler): 31 | # we override log_message() to show which process is handling the request 32 | def log_message(self, format, *args): 33 | note(format, *args) 34 | 35 | def serve_forever(server): 36 | note('starting server') 37 | try: 38 | server.serve_forever() 39 | except KeyboardInterrupt: 40 | pass 41 | 42 | 43 | def runpool(address, number_of_processes): 44 | # create a single server object -- children will each inherit a copy 45 | server = HTTPServer(address, RequestHandler) 46 | 47 | # create child processes to act as workers 48 | for i in range(number_of_processes-1): 49 | Process(target=serve_forever, args=(server,)).start() 50 | 51 | # main process also acts as a worker 52 | serve_forever(server) 53 | 54 | 55 | def test(): 56 | DIR = os.path.join(os.path.dirname(__file__), '..') 57 | ADDRESS = ('localhost', 8000) 58 | NUMBER_OF_PROCESSES = 4 59 | 60 | print 'Serving at http://%s:%d using %d worker processes' % \ 61 | (ADDRESS[0], ADDRESS[1], NUMBER_OF_PROCESSES) 62 | print 'To exit press Ctrl-' + ['C', 'Break'][sys.platform=='win32'] 63 | 64 | os.chdir(DIR) 65 | runpool(ADDRESS, NUMBER_OF_PROCESSES) 66 | 67 | 68 | if __name__ == '__main__': 69 | freeze_support() 70 | test() 71 | -------------------------------------------------------------------------------- /includes/mp_workers.py: -------------------------------------------------------------------------------- 1 | # 2 | # Simple example which uses a pool of workers to carry out some tasks. 3 | # 4 | # Notice that the results will probably not come out of the output 5 | # queue in the same in the same order as the corresponding tasks were 6 | # put on the input queue. If it is important to get the results back 7 | # in the original order then consider using `Pool.map()` or 8 | # `Pool.imap()` (which will save on the amount of code needed anyway). 9 | # 10 | # Copyright (c) 2006-2008, R Oudkerk 11 | # All rights reserved. 12 | # 13 | 14 | import time 15 | import random 16 | 17 | from multiprocessing import Process, Queue, current_process, freeze_support 18 | 19 | # 20 | # Function run by worker processes 21 | # 22 | 23 | def worker(input, output): 24 | for func, args in iter(input.get, 'STOP'): 25 | result = calculate(func, args) 26 | output.put(result) 27 | 28 | # 29 | # Function used to calculate result 30 | # 31 | 32 | def calculate(func, args): 33 | result = func(*args) 34 | return '%s says that %s%s = %s' % \ 35 | (current_process().name, func.__name__, args, result) 36 | 37 | # 38 | # Functions referenced by tasks 39 | # 40 | 41 | def mul(a, b): 42 | time.sleep(0.5*random.random()) 43 | return a * b 44 | 45 | def plus(a, b): 46 | time.sleep(0.5*random.random()) 47 | return a + b 48 | 49 | # 50 | # 51 | # 52 | 53 | def test(): 54 | NUMBER_OF_PROCESSES = 4 55 | TASKS1 = [(mul, (i, 7)) for i in range(20)] 56 | TASKS2 = [(plus, (i, 8)) for i in range(10)] 57 | 58 | # Create queues 59 | task_queue = Queue() 60 | done_queue = Queue() 61 | 62 | # Submit tasks 63 | for task in TASKS1: 64 | task_queue.put(task) 65 | 66 | # Start worker processes 67 | for i in range(NUMBER_OF_PROCESSES): 68 | Process(target=worker, args=(task_queue, done_queue)).start() 69 | 70 | # Get and print results 71 | print 'Unordered results:' 72 | for i in range(len(TASKS1)): 73 | print '\t', done_queue.get() 74 | 75 | # Add more tasks using `put()` 76 | for task in TASKS2: 77 | task_queue.put(task) 78 | 79 | # Get and print some more results 80 | for i in range(len(TASKS2)): 81 | print '\t', done_queue.get() 82 | 83 | # Tell child processes to stop 84 | for i in range(NUMBER_OF_PROCESSES): 85 | task_queue.put('STOP') 86 | 87 | 88 | if __name__ == '__main__': 89 | freeze_support() 90 | test() 91 | -------------------------------------------------------------------------------- /includes/noddy.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct { 4 | PyObject_HEAD 5 | /* Type-specific fields go here. */ 6 | } noddy_NoddyObject; 7 | 8 | static PyTypeObject noddy_NoddyType = { 9 | PyObject_HEAD_INIT(NULL) 10 | 0, /*ob_size*/ 11 | "noddy.Noddy", /*tp_name*/ 12 | sizeof(noddy_NoddyObject), /*tp_basicsize*/ 13 | 0, /*tp_itemsize*/ 14 | 0, /*tp_dealloc*/ 15 | 0, /*tp_print*/ 16 | 0, /*tp_getattr*/ 17 | 0, /*tp_setattr*/ 18 | 0, /*tp_compare*/ 19 | 0, /*tp_repr*/ 20 | 0, /*tp_as_number*/ 21 | 0, /*tp_as_sequence*/ 22 | 0, /*tp_as_mapping*/ 23 | 0, /*tp_hash */ 24 | 0, /*tp_call*/ 25 | 0, /*tp_str*/ 26 | 0, /*tp_getattro*/ 27 | 0, /*tp_setattro*/ 28 | 0, /*tp_as_buffer*/ 29 | Py_TPFLAGS_DEFAULT, /*tp_flags*/ 30 | "Noddy objects", /* tp_doc */ 31 | }; 32 | 33 | static PyMethodDef noddy_methods[] = { 34 | {NULL} /* Sentinel */ 35 | }; 36 | 37 | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ 38 | #define PyMODINIT_FUNC void 39 | #endif 40 | PyMODINIT_FUNC 41 | initnoddy(void) 42 | { 43 | PyObject* m; 44 | 45 | noddy_NoddyType.tp_new = PyType_GenericNew; 46 | if (PyType_Ready(&noddy_NoddyType) < 0) 47 | return; 48 | 49 | m = Py_InitModule3("noddy", noddy_methods, 50 | "Example module that creates an extension type."); 51 | 52 | Py_INCREF(&noddy_NoddyType); 53 | PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType); 54 | } 55 | -------------------------------------------------------------------------------- /includes/run-func.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main(int argc, char *argv[]) 5 | { 6 | PyObject *pName, *pModule, *pDict, *pFunc; 7 | PyObject *pArgs, *pValue; 8 | int i; 9 | 10 | if (argc < 3) { 11 | fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); 12 | return 1; 13 | } 14 | 15 | Py_Initialize(); 16 | pName = PyString_FromString(argv[1]); 17 | /* Error checking of pName left out */ 18 | 19 | pModule = PyImport_Import(pName); 20 | Py_DECREF(pName); 21 | 22 | if (pModule != NULL) { 23 | pFunc = PyObject_GetAttrString(pModule, argv[2]); 24 | /* pFunc is a new reference */ 25 | 26 | if (pFunc && PyCallable_Check(pFunc)) { 27 | pArgs = PyTuple_New(argc - 3); 28 | for (i = 0; i < argc - 3; ++i) { 29 | pValue = PyInt_FromLong(atoi(argv[i + 3])); 30 | if (!pValue) { 31 | Py_DECREF(pArgs); 32 | Py_DECREF(pModule); 33 | fprintf(stderr, "Cannot convert argument\n"); 34 | return 1; 35 | } 36 | /* pValue reference stolen here: */ 37 | PyTuple_SetItem(pArgs, i, pValue); 38 | } 39 | pValue = PyObject_CallObject(pFunc, pArgs); 40 | Py_DECREF(pArgs); 41 | if (pValue != NULL) { 42 | printf("Result of call: %ld\n", PyInt_AsLong(pValue)); 43 | Py_DECREF(pValue); 44 | } 45 | else { 46 | Py_DECREF(pFunc); 47 | Py_DECREF(pModule); 48 | PyErr_Print(); 49 | fprintf(stderr,"Call failed\n"); 50 | return 1; 51 | } 52 | } 53 | else { 54 | if (PyErr_Occurred()) 55 | PyErr_Print(); 56 | fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); 57 | } 58 | Py_XDECREF(pFunc); 59 | Py_DECREF(pModule); 60 | } 61 | else { 62 | PyErr_Print(); 63 | fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); 64 | return 1; 65 | } 66 | Py_Finalize(); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /includes/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | setup(name="noddy", version="1.0", 3 | ext_modules=[ 4 | Extension("noddy", ["noddy.c"]), 5 | Extension("noddy2", ["noddy2.c"]), 6 | Extension("noddy3", ["noddy3.c"]), 7 | Extension("noddy4", ["noddy4.c"]), 8 | ]) 9 | -------------------------------------------------------------------------------- /includes/sqlite3/adapter_datetime.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import datetime, time 3 | 4 | def adapt_datetime(ts): 5 | return time.mktime(ts.timetuple()) 6 | 7 | sqlite3.register_adapter(datetime.datetime, adapt_datetime) 8 | 9 | con = sqlite3.connect(":memory:") 10 | cur = con.cursor() 11 | 12 | now = datetime.datetime.now() 13 | cur.execute("select ?", (now,)) 14 | print cur.fetchone()[0] 15 | -------------------------------------------------------------------------------- /includes/sqlite3/adapter_point_1.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class Point(object): 4 | def __init__(self, x, y): 5 | self.x, self.y = x, y 6 | 7 | def __conform__(self, protocol): 8 | if protocol is sqlite3.PrepareProtocol: 9 | return "%f;%f" % (self.x, self.y) 10 | 11 | con = sqlite3.connect(":memory:") 12 | cur = con.cursor() 13 | 14 | p = Point(4.0, -3.2) 15 | cur.execute("select ?", (p,)) 16 | print cur.fetchone()[0] 17 | -------------------------------------------------------------------------------- /includes/sqlite3/adapter_point_2.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class Point(object): 4 | def __init__(self, x, y): 5 | self.x, self.y = x, y 6 | 7 | def adapt_point(point): 8 | return "%f;%f" % (point.x, point.y) 9 | 10 | sqlite3.register_adapter(Point, adapt_point) 11 | 12 | con = sqlite3.connect(":memory:") 13 | cur = con.cursor() 14 | 15 | p = Point(4.0, -3.2) 16 | cur.execute("select ?", (p,)) 17 | print cur.fetchone()[0] 18 | -------------------------------------------------------------------------------- /includes/sqlite3/collation_reverse.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | def collate_reverse(string1, string2): 4 | return -cmp(string1, string2) 5 | 6 | con = sqlite3.connect(":memory:") 7 | con.create_collation("reverse", collate_reverse) 8 | 9 | cur = con.cursor() 10 | cur.execute("create table test(x)") 11 | cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) 12 | cur.execute("select x from test order by x collate reverse") 13 | for row in cur: 14 | print row 15 | con.close() 16 | -------------------------------------------------------------------------------- /includes/sqlite3/complete_statement.py: -------------------------------------------------------------------------------- 1 | # A minimal SQLite shell for experiments 2 | 3 | import sqlite3 4 | 5 | con = sqlite3.connect(":memory:") 6 | con.isolation_level = None 7 | cur = con.cursor() 8 | 9 | buffer = "" 10 | 11 | print "Enter your SQL commands to execute in sqlite3." 12 | print "Enter a blank line to exit." 13 | 14 | while True: 15 | line = raw_input() 16 | if line == "": 17 | break 18 | buffer += line 19 | if sqlite3.complete_statement(buffer): 20 | try: 21 | buffer = buffer.strip() 22 | cur.execute(buffer) 23 | 24 | if buffer.lstrip().upper().startswith("SELECT"): 25 | print cur.fetchall() 26 | except sqlite3.Error, e: 27 | print "An error occurred:", e.args[0] 28 | buffer = "" 29 | 30 | con.close() 31 | -------------------------------------------------------------------------------- /includes/sqlite3/connect_db_1.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | -------------------------------------------------------------------------------- /includes/sqlite3/connect_db_2.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect(":memory:") 4 | -------------------------------------------------------------------------------- /includes/sqlite3/converter_point.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class Point(object): 4 | def __init__(self, x, y): 5 | self.x, self.y = x, y 6 | 7 | def __repr__(self): 8 | return "(%f;%f)" % (self.x, self.y) 9 | 10 | def adapt_point(point): 11 | return "%f;%f" % (point.x, point.y) 12 | 13 | def convert_point(s): 14 | x, y = map(float, s.split(";")) 15 | return Point(x, y) 16 | 17 | # Register the adapter 18 | sqlite3.register_adapter(Point, adapt_point) 19 | 20 | # Register the converter 21 | sqlite3.register_converter("point", convert_point) 22 | 23 | p = Point(4.0, -3.2) 24 | 25 | ######################### 26 | # 1) Using declared types 27 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) 28 | cur = con.cursor() 29 | cur.execute("create table test(p point)") 30 | 31 | cur.execute("insert into test(p) values (?)", (p,)) 32 | cur.execute("select p from test") 33 | print "with declared types:", cur.fetchone()[0] 34 | cur.close() 35 | con.close() 36 | 37 | ####################### 38 | # 1) Using column names 39 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) 40 | cur = con.cursor() 41 | cur.execute("create table test(p)") 42 | 43 | cur.execute("insert into test(p) values (?)", (p,)) 44 | cur.execute('select p as "p [point]" from test') 45 | print "with column names:", cur.fetchone()[0] 46 | cur.close() 47 | con.close() 48 | -------------------------------------------------------------------------------- /includes/sqlite3/countcursors.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class CountCursorsConnection(sqlite3.Connection): 4 | def __init__(self, *args, **kwargs): 5 | sqlite3.Connection.__init__(self, *args, **kwargs) 6 | self.numcursors = 0 7 | 8 | def cursor(self, *args, **kwargs): 9 | self.numcursors += 1 10 | return sqlite3.Connection.cursor(self, *args, **kwargs) 11 | 12 | con = sqlite3.connect(":memory:", factory=CountCursorsConnection) 13 | cur1 = con.cursor() 14 | cur2 = con.cursor() 15 | print con.numcursors 16 | -------------------------------------------------------------------------------- /includes/sqlite3/createdb.py: -------------------------------------------------------------------------------- 1 | # Not referenced from the documentation, but builds the database file the other 2 | # code snippets expect. 3 | 4 | import sqlite3 5 | import os 6 | 7 | DB_FILE = "mydb" 8 | 9 | if os.path.exists(DB_FILE): 10 | os.remove(DB_FILE) 11 | 12 | con = sqlite3.connect(DB_FILE) 13 | cur = con.cursor() 14 | cur.execute(""" 15 | create table people 16 | ( 17 | name_last varchar(20), 18 | age integer 19 | ) 20 | """) 21 | 22 | cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)") 23 | cur.execute("insert into people (name_last, age) values ('Putin', 51)") 24 | 25 | con.commit() 26 | 27 | cur.close() 28 | con.close() 29 | -------------------------------------------------------------------------------- /includes/sqlite3/ctx_manager.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect(":memory:") 4 | con.execute("create table person (id integer primary key, firstname varchar unique)") 5 | 6 | # Successful, con.commit() is called automatically afterwards 7 | with con: 8 | con.execute("insert into person(firstname) values (?)", ("Joe",)) 9 | 10 | # con.rollback() is called after the with block finishes with an exception, the 11 | # exception is still raised and must be catched 12 | try: 13 | with con: 14 | con.execute("insert into person(firstname) values (?)", ("Joe",)) 15 | except sqlite3.IntegrityError: 16 | print "couldn't add Joe twice" 17 | -------------------------------------------------------------------------------- /includes/sqlite3/execsql_fetchonerow.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | 5 | cur = con.cursor() 6 | SELECT = "select name_last, age from people order by age, name_last" 7 | 8 | # 1. Iterate over the rows available from the cursor, unpacking the 9 | # resulting sequences to yield their elements (name_last, age): 10 | cur.execute(SELECT) 11 | for (name_last, age) in cur: 12 | print '%s is %d years old.' % (name_last, age) 13 | 14 | # 2. Equivalently: 15 | cur.execute(SELECT) 16 | for row in cur: 17 | print '%s is %d years old.' % (row[0], row[1]) 18 | -------------------------------------------------------------------------------- /includes/sqlite3/execsql_printall_1.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | # Create a connection to the database file "mydb": 4 | con = sqlite3.connect("mydb") 5 | 6 | # Get a Cursor object that operates in the context of Connection con: 7 | cur = con.cursor() 8 | 9 | # Execute the SELECT statement: 10 | cur.execute("select * from people order by age") 11 | 12 | # Retrieve all rows as a sequence and print that sequence: 13 | print cur.fetchall() 14 | -------------------------------------------------------------------------------- /includes/sqlite3/execute_1.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | 5 | cur = con.cursor() 6 | 7 | who = "Yeltsin" 8 | age = 72 9 | 10 | cur.execute("select name_last, age from people where name_last=? and age=?", (who, age)) 11 | print cur.fetchone() 12 | -------------------------------------------------------------------------------- /includes/sqlite3/execute_2.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | 5 | cur = con.cursor() 6 | 7 | who = "Yeltsin" 8 | age = 72 9 | 10 | cur.execute("select name_last, age from people where name_last=:who and age=:age", 11 | {"who": who, "age": age}) 12 | print cur.fetchone() 13 | -------------------------------------------------------------------------------- /includes/sqlite3/execute_3.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | 5 | cur = con.cursor() 6 | 7 | who = "Yeltsin" 8 | age = 72 9 | 10 | cur.execute("select name_last, age from people where name_last=:who and age=:age", 11 | locals()) 12 | print cur.fetchone() 13 | -------------------------------------------------------------------------------- /includes/sqlite3/executemany_1.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class IterChars: 4 | def __init__(self): 5 | self.count = ord('a') 6 | 7 | def __iter__(self): 8 | return self 9 | 10 | def next(self): 11 | if self.count > ord('z'): 12 | raise StopIteration 13 | self.count += 1 14 | return (chr(self.count - 1),) # this is a 1-tuple 15 | 16 | con = sqlite3.connect(":memory:") 17 | cur = con.cursor() 18 | cur.execute("create table characters(c)") 19 | 20 | theIter = IterChars() 21 | cur.executemany("insert into characters(c) values (?)", theIter) 22 | 23 | cur.execute("select c from characters") 24 | print cur.fetchall() 25 | -------------------------------------------------------------------------------- /includes/sqlite3/executemany_2.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | def char_generator(): 4 | import string 5 | for c in string.letters[:26]: 6 | yield (c,) 7 | 8 | con = sqlite3.connect(":memory:") 9 | cur = con.cursor() 10 | cur.execute("create table characters(c)") 11 | 12 | cur.executemany("insert into characters(c) values (?)", char_generator()) 13 | 14 | cur.execute("select c from characters") 15 | print cur.fetchall() 16 | -------------------------------------------------------------------------------- /includes/sqlite3/executescript.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect(":memory:") 4 | cur = con.cursor() 5 | cur.executescript(""" 6 | create table person( 7 | firstname, 8 | lastname, 9 | age 10 | ); 11 | 12 | create table book( 13 | title, 14 | author, 15 | published 16 | ); 17 | 18 | insert into book(title, author, published) 19 | values ( 20 | 'Dirk Gently''s Holistic Detective Agency', 21 | 'Douglas Adams', 22 | 1987 23 | ); 24 | """) 25 | -------------------------------------------------------------------------------- /includes/sqlite3/insert_more_people.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | 5 | cur = con.cursor() 6 | 7 | newPeople = ( 8 | ('Lebed' , 53), 9 | ('Zhirinovsky' , 57), 10 | ) 11 | 12 | for person in newPeople: 13 | cur.execute("insert into people (name_last, age) values (?, ?)", person) 14 | 15 | # The changes will not be saved unless the transaction is committed explicitly: 16 | con.commit() 17 | -------------------------------------------------------------------------------- /includes/sqlite3/load_extension.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect(":memory:") 4 | 5 | # enable extension loading 6 | con.enable_load_extension(True) 7 | 8 | # Load the fulltext search extension 9 | con.execute("select load_extension('./fts3.so')") 10 | 11 | # alternatively you can load the extension using an API call: 12 | # con.load_extension("./fts3.so") 13 | 14 | # disable extension laoding again 15 | con.enable_load_extension(False) 16 | 17 | # example from SQLite wiki 18 | con.execute("create virtual table recipe using fts3(name, ingredients)") 19 | con.executescript(""" 20 | insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes'); 21 | insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery'); 22 | insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour'); 23 | insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter'); 24 | """) 25 | for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"): 26 | print row 27 | -------------------------------------------------------------------------------- /includes/sqlite3/md5func.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import md5 3 | 4 | def md5sum(t): 5 | return md5.md5(t).hexdigest() 6 | 7 | con = sqlite3.connect(":memory:") 8 | con.create_function("md5", 1, md5sum) 9 | cur = con.cursor() 10 | cur.execute("select md5(?)", ("foo",)) 11 | print cur.fetchone()[0] 12 | -------------------------------------------------------------------------------- /includes/sqlite3/mysumaggr.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | class MySum: 4 | def __init__(self): 5 | self.count = 0 6 | 7 | def step(self, value): 8 | self.count += value 9 | 10 | def finalize(self): 11 | return self.count 12 | 13 | con = sqlite3.connect(":memory:") 14 | con.create_aggregate("mysum", 1, MySum) 15 | cur = con.cursor() 16 | cur.execute("create table test(i)") 17 | cur.execute("insert into test(i) values (1)") 18 | cur.execute("insert into test(i) values (2)") 19 | cur.execute("select mysum(i) from test") 20 | print cur.fetchone()[0] 21 | -------------------------------------------------------------------------------- /includes/sqlite3/parse_colnames.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import datetime 3 | 4 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) 5 | cur = con.cursor() 6 | cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),)) 7 | dt = cur.fetchone()[0] 8 | print dt, type(dt) 9 | -------------------------------------------------------------------------------- /includes/sqlite3/pysqlite_datetime.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import datetime 3 | 4 | con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) 5 | cur = con.cursor() 6 | cur.execute("create table test(d date, ts timestamp)") 7 | 8 | today = datetime.date.today() 9 | now = datetime.datetime.now() 10 | 11 | cur.execute("insert into test(d, ts) values (?, ?)", (today, now)) 12 | cur.execute("select d, ts from test") 13 | row = cur.fetchone() 14 | print today, "=>", row[0], type(row[0]) 15 | print now, "=>", row[1], type(row[1]) 16 | 17 | cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"') 18 | row = cur.fetchone() 19 | print "current_date", row[0], type(row[0]) 20 | print "current_timestamp", row[1], type(row[1]) 21 | -------------------------------------------------------------------------------- /includes/sqlite3/row_factory.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | def dict_factory(cursor, row): 4 | d = {} 5 | for idx, col in enumerate(cursor.description): 6 | d[col[0]] = row[idx] 7 | return d 8 | 9 | con = sqlite3.connect(":memory:") 10 | con.row_factory = dict_factory 11 | cur = con.cursor() 12 | cur.execute("select 1 as a") 13 | print cur.fetchone()["a"] 14 | -------------------------------------------------------------------------------- /includes/sqlite3/rowclass.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect("mydb") 4 | con.row_factory = sqlite3.Row 5 | 6 | cur = con.cursor() 7 | cur.execute("select name_last, age from people") 8 | for row in cur: 9 | assert row[0] == row["name_last"] 10 | assert row["name_last"] == row["nAmE_lAsT"] 11 | assert row[1] == row["age"] 12 | assert row[1] == row["AgE"] 13 | -------------------------------------------------------------------------------- /includes/sqlite3/shared_cache.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | # The shared cache is only available in SQLite versions 3.3.3 or later 4 | # See the SQLite documentation for details. 5 | 6 | sqlite3.enable_shared_cache(True) 7 | -------------------------------------------------------------------------------- /includes/sqlite3/shortcut_methods.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | persons = [ 4 | ("Hugo", "Boss"), 5 | ("Calvin", "Klein") 6 | ] 7 | 8 | con = sqlite3.connect(":memory:") 9 | 10 | # Create the table 11 | con.execute("create table person(firstname, lastname)") 12 | 13 | # Fill the table 14 | con.executemany("insert into person(firstname, lastname) values (?, ?)", persons) 15 | 16 | # Print the table contents 17 | for row in con.execute("select firstname, lastname from person"): 18 | print row 19 | 20 | # Using a dummy WHERE clause to not let SQLite take the shortcut table deletes. 21 | print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows" 22 | -------------------------------------------------------------------------------- /includes/sqlite3/simple_tableprinter.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | FIELD_MAX_WIDTH = 20 4 | TABLE_NAME = 'people' 5 | SELECT = 'select * from %s order by age, name_last' % TABLE_NAME 6 | 7 | con = sqlite3.connect("mydb") 8 | 9 | cur = con.cursor() 10 | cur.execute(SELECT) 11 | 12 | # Print a header. 13 | for fieldDesc in cur.description: 14 | print fieldDesc[0].ljust(FIELD_MAX_WIDTH) , 15 | print # Finish the header with a newline. 16 | print '-' * 78 17 | 18 | # For each row, print the value of each field left-justified within 19 | # the maximum possible width of that field. 20 | fieldIndices = range(len(cur.description)) 21 | for row in cur: 22 | for fieldIndex in fieldIndices: 23 | fieldValue = str(row[fieldIndex]) 24 | print fieldValue.ljust(FIELD_MAX_WIDTH) , 25 | 26 | print # Finish the row with a newline. 27 | -------------------------------------------------------------------------------- /includes/sqlite3/text_factory.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | con = sqlite3.connect(":memory:") 4 | cur = con.cursor() 5 | 6 | # Create the table 7 | con.execute("create table person(lastname, firstname)") 8 | 9 | AUSTRIA = u"\xd6sterreich" 10 | 11 | # by default, rows are returned as Unicode 12 | cur.execute("select ?", (AUSTRIA,)) 13 | row = cur.fetchone() 14 | assert row[0] == AUSTRIA 15 | 16 | # but we can make sqlite3 always return bytestrings ... 17 | con.text_factory = str 18 | cur.execute("select ?", (AUSTRIA,)) 19 | row = cur.fetchone() 20 | assert type(row[0]) == str 21 | # the bytestrings will be encoded in UTF-8, unless you stored garbage in the 22 | # database ... 23 | assert row[0] == AUSTRIA.encode("utf-8") 24 | 25 | # we can also implement a custom text_factory ... 26 | # here we implement one that will ignore Unicode characters that cannot be 27 | # decoded from UTF-8 28 | con.text_factory = lambda x: unicode(x, "utf-8", "ignore") 29 | cur.execute("select ?", ("this is latin1 and would normally create errors" + 30 | u"\xe4\xf6\xfc".encode("latin1"),)) 31 | row = cur.fetchone() 32 | assert type(row[0]) == unicode 33 | 34 | # sqlite3 offers a built-in optimized text_factory that will return bytestring 35 | # objects, if the data is in ASCII only, and otherwise return unicode objects 36 | con.text_factory = sqlite3.OptimizedUnicode 37 | cur.execute("select ?", (AUSTRIA,)) 38 | row = cur.fetchone() 39 | assert type(row[0]) == unicode 40 | 41 | cur.execute("select ?", ("Germany",)) 42 | row = cur.fetchone() 43 | assert type(row[0]) == str 44 | -------------------------------------------------------------------------------- /includes/typestruct.h: -------------------------------------------------------------------------------- 1 | typedef struct _typeobject { 2 | PyObject_VAR_HEAD 3 | char *tp_name; /* For printing, in format "." */ 4 | int tp_basicsize, tp_itemsize; /* For allocation */ 5 | 6 | /* Methods to implement standard operations */ 7 | 8 | destructor tp_dealloc; 9 | printfunc tp_print; 10 | getattrfunc tp_getattr; 11 | setattrfunc tp_setattr; 12 | cmpfunc tp_compare; 13 | reprfunc tp_repr; 14 | 15 | /* Method suites for standard classes */ 16 | 17 | PyNumberMethods *tp_as_number; 18 | PySequenceMethods *tp_as_sequence; 19 | PyMappingMethods *tp_as_mapping; 20 | 21 | /* More standard operations (here for binary compatibility) */ 22 | 23 | hashfunc tp_hash; 24 | ternaryfunc tp_call; 25 | reprfunc tp_str; 26 | getattrofunc tp_getattro; 27 | setattrofunc tp_setattro; 28 | 29 | /* Functions to access object as input/output buffer */ 30 | PyBufferProcs *tp_as_buffer; 31 | 32 | /* Flags to define presence of optional/expanded features */ 33 | long tp_flags; 34 | 35 | char *tp_doc; /* Documentation string */ 36 | 37 | /* Assigned meaning in release 2.0 */ 38 | /* call function for all accessible objects */ 39 | traverseproc tp_traverse; 40 | 41 | /* delete references to contained objects */ 42 | inquiry tp_clear; 43 | 44 | /* Assigned meaning in release 2.1 */ 45 | /* rich comparisons */ 46 | richcmpfunc tp_richcompare; 47 | 48 | /* weak reference enabler */ 49 | long tp_weaklistoffset; 50 | 51 | /* Added in release 2.2 */ 52 | /* Iterators */ 53 | getiterfunc tp_iter; 54 | iternextfunc tp_iternext; 55 | 56 | /* Attribute descriptor and subclassing stuff */ 57 | struct PyMethodDef *tp_methods; 58 | struct PyMemberDef *tp_members; 59 | struct PyGetSetDef *tp_getset; 60 | struct _typeobject *tp_base; 61 | PyObject *tp_dict; 62 | descrgetfunc tp_descr_get; 63 | descrsetfunc tp_descr_set; 64 | long tp_dictoffset; 65 | initproc tp_init; 66 | allocfunc tp_alloc; 67 | newfunc tp_new; 68 | freefunc tp_free; /* Low-level free-memory routine */ 69 | inquiry tp_is_gc; /* For PyObject_IS_GC */ 70 | PyObject *tp_bases; 71 | PyObject *tp_mro; /* method resolution order */ 72 | PyObject *tp_cache; 73 | PyObject *tp_subclasses; 74 | PyObject *tp_weaklist; 75 | 76 | } PyTypeObject; 77 | -------------------------------------------------------------------------------- /library/__builtin__.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`__builtin__` --- Built-in objects 3 | ======================================= 4 | 5 | .. module:: __builtin__ 6 | :synopsis: The module that provides the built-in namespace. 7 | 8 | 9 | This module provides direct access to all 'built-in' identifiers of Python; for 10 | example, ``__builtin__.open`` is the full name for the built-in function 11 | :func:`open`. 12 | 13 | This module is not normally accessed explicitly by most applications, but can be 14 | useful in modules that provide objects with the same name as a built-in value, 15 | but in which the built-in of that name is also needed. For example, in a module 16 | that wants to implement an :func:`open` function that wraps the built-in 17 | :func:`open`, this module can be used directly:: 18 | 19 | import __builtin__ 20 | 21 | def open(path): 22 | f = __builtin__.open(path, 'r') 23 | return UpperCaser(f) 24 | 25 | class UpperCaser: 26 | '''Wrapper around a file that converts output to upper-case.''' 27 | 28 | def __init__(self, f): 29 | self._f = f 30 | 31 | def read(self, count=-1): 32 | return self._f.read(count).upper() 33 | 34 | # ... 35 | 36 | .. impl-detail:: 37 | 38 | Most modules have the name ``__builtins__`` (note the ``'s'``) made available 39 | as part of their globals. The value of ``__builtins__`` is normally either 40 | this module or the value of this modules's :attr:`__dict__` attribute. Since 41 | this is an implementation detail, it may not be used by alternate 42 | implementations of Python. 43 | -------------------------------------------------------------------------------- /library/__main__.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`__main__` --- Top-level script environment 3 | ================================================ 4 | 5 | .. module:: __main__ 6 | :synopsis: The environment where the top-level script is run. 7 | 8 | 9 | This module represents the (otherwise anonymous) scope in which the 10 | interpreter's main program executes --- commands read either from standard 11 | input, from a script file, or from an interactive prompt. It is this 12 | environment in which the idiomatic "conditional script" stanza causes a script 13 | to run:: 14 | 15 | if __name__ == "__main__": 16 | main() 17 | 18 | -------------------------------------------------------------------------------- /library/allos.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _allos: 3 | 4 | ********************************* 5 | Generic Operating System Services 6 | ********************************* 7 | 8 | The modules described in this chapter provide interfaces to operating system 9 | features that are available on (almost) all operating systems, such as files and 10 | a clock. The interfaces are generally modeled after the Unix or C interfaces, 11 | but they are available on most other systems as well. Here's an overview: 12 | 13 | 14 | .. toctree:: 15 | 16 | os.rst 17 | io.rst 18 | time.rst 19 | argparse.rst 20 | optparse.rst 21 | getopt.rst 22 | logging.rst 23 | logging.config.rst 24 | logging.handlers.rst 25 | getpass.rst 26 | curses.rst 27 | curses.ascii.rst 28 | curses.panel.rst 29 | platform.rst 30 | errno.rst 31 | ctypes.rst 32 | -------------------------------------------------------------------------------- /library/archiving.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _archiving: 3 | 4 | ****************************** 5 | Data Compression and Archiving 6 | ****************************** 7 | 8 | The modules described in this chapter support data compression with the zlib, 9 | gzip, and bzip2 algorithms, and the creation of ZIP- and tar-format archives. 10 | 11 | 12 | .. toctree:: 13 | 14 | zlib.rst 15 | gzip.rst 16 | bz2.rst 17 | zipfile.rst 18 | tarfile.rst 19 | -------------------------------------------------------------------------------- /library/autogil.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`autoGIL` --- Global Interpreter Lock handling in event loops 3 | ================================================================== 4 | 5 | .. module:: autoGIL 6 | :platform: Mac 7 | :synopsis: Global Interpreter Lock handling in event loops. 8 | :deprecated: 9 | .. moduleauthor:: Just van Rossum 10 | 11 | 12 | The :mod:`autoGIL` module provides a function :func:`installAutoGIL` that 13 | automatically locks and unlocks Python's :term:`Global Interpreter Lock` when 14 | running an event loop. 15 | 16 | .. note:: 17 | 18 | This module has been removed in Python 3.x. 19 | 20 | 21 | .. exception:: AutoGILError 22 | 23 | Raised if the observer callback cannot be installed, for example because the 24 | current thread does not have a run loop. 25 | 26 | 27 | .. function:: installAutoGIL() 28 | 29 | Install an observer callback in the event loop (CFRunLoop) for the current 30 | thread, that will lock and unlock the Global Interpreter Lock (GIL) at 31 | appropriate times, allowing other Python threads to run while the event loop is 32 | idle. 33 | 34 | Availability: OSX 10.1 or later. 35 | 36 | -------------------------------------------------------------------------------- /library/bastion.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`Bastion` --- Restricting access to objects 3 | ================================================ 4 | 5 | .. module:: Bastion 6 | :synopsis: Providing restricted access to objects. 7 | :deprecated: 8 | 9 | .. deprecated:: 2.6 10 | The :mod:`Bastion` module has been removed in Python 3.0. 11 | 12 | .. moduleauthor:: Barry Warsaw 13 | 14 | 15 | .. versionchanged:: 2.3 16 | Disabled module. 17 | 18 | .. note:: 19 | 20 | The documentation has been left in place to help in reading old code that uses 21 | the module. 22 | 23 | According to the dictionary, a bastion is "a fortified area or position", or 24 | "something that is considered a stronghold." It's a suitable name for this 25 | module, which provides a way to forbid access to certain attributes of an 26 | object. It must always be used with the :mod:`rexec` module, in order to allow 27 | restricted-mode programs access to certain safe attributes of an object, while 28 | denying access to other, unsafe attributes. 29 | 30 | .. I'm concerned that the word 'bastion' won't be understood by people 31 | .. for whom English is a second language, making the module name 32 | .. somewhat mysterious. Thus, the brief definition... --amk 33 | 34 | .. I've punted on the issue of documenting keyword arguments for now. 35 | 36 | 37 | .. function:: Bastion(object[, filter[, name[, class]]]) 38 | 39 | Protect the object *object*, returning a bastion for the object. Any attempt to 40 | access one of the object's attributes will have to be approved by the *filter* 41 | function; if the access is denied an :exc:`AttributeError` exception will be 42 | raised. 43 | 44 | If present, *filter* must be a function that accepts a string containing an 45 | attribute name, and returns true if access to that attribute will be permitted; 46 | if *filter* returns false, the access is denied. The default filter denies 47 | access to any function beginning with an underscore (``'_'``). The bastion's 48 | string representation will be ```` if a value for *name* is 49 | provided; otherwise, ``repr(object)`` will be used. 50 | 51 | *class*, if present, should be a subclass of :class:`BastionClass`; see the 52 | code in :file:`bastion.py` for the details. Overriding the default 53 | :class:`BastionClass` will rarely be required. 54 | 55 | 56 | .. class:: BastionClass(getfunc, name) 57 | 58 | Class which actually implements bastion objects. This is the default class used 59 | by :func:`Bastion`. The *getfunc* parameter is a function which returns the 60 | value of an attribute which should be exposed to the restricted execution 61 | environment when called with the name of the attribute as the only parameter. 62 | *name* is used to construct the :func:`repr` of the :class:`BastionClass` 63 | instance. 64 | 65 | -------------------------------------------------------------------------------- /library/binhex.rst: -------------------------------------------------------------------------------- 1 | :mod:`binhex` --- Encode and decode binhex4 files 2 | ================================================= 3 | 4 | .. module:: binhex 5 | :synopsis: Encode and decode files in binhex4 format. 6 | 7 | 8 | This module encodes and decodes files in binhex4 format, a format allowing 9 | representation of Macintosh files in ASCII. On the Macintosh, both forks of a 10 | file and the finder information are encoded (or decoded), on other platforms 11 | only the data fork is handled. 12 | 13 | .. note:: 14 | 15 | In Python 3.x, special Macintosh support has been removed. 16 | 17 | 18 | The :mod:`binhex` module defines the following functions: 19 | 20 | 21 | .. function:: binhex(input, output) 22 | 23 | Convert a binary file with filename *input* to binhex file *output*. The 24 | *output* parameter can either be a filename or a file-like object (any object 25 | supporting a :meth:`write` and :meth:`close` method). 26 | 27 | 28 | .. function:: hexbin(input[, output]) 29 | 30 | Decode a binhex file *input*. *input* may be a filename or a file-like object 31 | supporting :meth:`read` and :meth:`close` methods. The resulting file is written 32 | to a file named *output*, unless the argument is omitted in which case the 33 | output filename is read from the binhex file. 34 | 35 | The following exception is also defined: 36 | 37 | 38 | .. exception:: Error 39 | 40 | Exception raised when something can't be encoded using the binhex format (for 41 | example, a filename is too long to fit in the filename field), or when input is 42 | not properly encoded binhex data. 43 | 44 | 45 | .. seealso:: 46 | 47 | Module :mod:`binascii` 48 | Support module containing ASCII-to-binary and binary-to-ASCII conversions. 49 | 50 | 51 | .. _binhex-notes: 52 | 53 | Notes 54 | ----- 55 | 56 | There is an alternative, more powerful interface to the coder and decoder, see 57 | the source for details. 58 | 59 | If you code or decode textfiles on non-Macintosh platforms they will still use 60 | the old Macintosh newline convention (carriage-return as end of line). 61 | 62 | As of this writing, :func:`hexbin` appears to not work in all cases. 63 | 64 | -------------------------------------------------------------------------------- /library/colorpicker.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`ColorPicker` --- Color selection dialog 3 | ============================================= 4 | 5 | .. module:: ColorPicker 6 | :platform: Mac 7 | :synopsis: Interface to the standard color selection dialog. 8 | :deprecated: 9 | .. moduleauthor:: Just van Rossum 10 | .. sectionauthor:: Fred L. Drake, Jr. 11 | 12 | 13 | The :mod:`ColorPicker` module provides access to the standard color picker 14 | dialog. 15 | 16 | .. note:: 17 | 18 | This module has been removed in Python 3.x. 19 | 20 | 21 | .. function:: GetColor(prompt, rgb) 22 | 23 | Show a standard color selection dialog and allow the user to select a color. 24 | The user is given instruction by the *prompt* string, and the default color is 25 | set to *rgb*. *rgb* must be a tuple giving the red, green, and blue components 26 | of the color. :func:`GetColor` returns a tuple giving the user's selected color 27 | and a flag indicating whether they accepted the selection of cancelled. 28 | 29 | -------------------------------------------------------------------------------- /library/colorsys.rst: -------------------------------------------------------------------------------- 1 | :mod:`colorsys` --- Conversions between color systems 2 | ===================================================== 3 | 4 | .. module:: colorsys 5 | :synopsis: Conversion functions between RGB and other color systems. 6 | .. sectionauthor:: David Ascher 7 | 8 | 9 | The :mod:`colorsys` module defines bidirectional conversions of color values 10 | between colors expressed in the RGB (Red Green Blue) color space used in 11 | computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness 12 | Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color 13 | spaces are floating point values. In the YIQ space, the Y coordinate is between 14 | 0 and 1, but the I and Q coordinates can be positive or negative. In all other 15 | spaces, the coordinates are all between 0 and 1. 16 | 17 | .. seealso:: 18 | 19 | More information about color spaces can be found at 20 | http://www.poynton.com/ColorFAQ.html and 21 | http://www.cambridgeincolour.com/tutorials/color-spaces.htm. 22 | 23 | The :mod:`colorsys` module defines the following functions: 24 | 25 | 26 | .. function:: rgb_to_yiq(r, g, b) 27 | 28 | Convert the color from RGB coordinates to YIQ coordinates. 29 | 30 | 31 | .. function:: yiq_to_rgb(y, i, q) 32 | 33 | Convert the color from YIQ coordinates to RGB coordinates. 34 | 35 | 36 | .. function:: rgb_to_hls(r, g, b) 37 | 38 | Convert the color from RGB coordinates to HLS coordinates. 39 | 40 | 41 | .. function:: hls_to_rgb(h, l, s) 42 | 43 | Convert the color from HLS coordinates to RGB coordinates. 44 | 45 | 46 | .. function:: rgb_to_hsv(r, g, b) 47 | 48 | Convert the color from RGB coordinates to HSV coordinates. 49 | 50 | 51 | .. function:: hsv_to_rgb(h, s, v) 52 | 53 | Convert the color from HSV coordinates to RGB coordinates. 54 | 55 | Example:: 56 | 57 | >>> import colorsys 58 | >>> colorsys.rgb_to_hsv(.3, .4, .2) 59 | (0.25, 0.5, 0.4) 60 | >>> colorsys.hsv_to_rgb(0.25, 0.5, 0.4) 61 | (0.3, 0.4, 0.2) 62 | -------------------------------------------------------------------------------- /library/commands.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`commands` --- Utilities for running commands 3 | ================================================== 4 | 5 | .. module:: commands 6 | :platform: Unix 7 | :synopsis: Utility functions for running external commands. 8 | :deprecated: 9 | 10 | .. deprecated:: 2.6 11 | The :mod:`commands` module has been removed in Python 3.0. Use the 12 | :mod:`subprocess` module instead. 13 | 14 | .. sectionauthor:: Sue Williams 15 | 16 | 17 | The :mod:`commands` module contains wrapper functions for :func:`os.popen` which 18 | take a system command as a string and return any output generated by the command 19 | and, optionally, the exit status. 20 | 21 | The :mod:`subprocess` module provides more powerful facilities for spawning new 22 | processes and retrieving their results. Using the :mod:`subprocess` module is 23 | preferable to using the :mod:`commands` module. 24 | 25 | .. note:: 26 | 27 | In Python 3.x, :func:`getstatus` and two undocumented functions 28 | (:func:`mk2arg` and :func:`mkarg`) have been removed. Also, 29 | :func:`getstatusoutput` and :func:`getoutput` have been moved to the 30 | :mod:`subprocess` module. 31 | 32 | The :mod:`commands` module defines the following functions: 33 | 34 | 35 | .. function:: getstatusoutput(cmd) 36 | 37 | Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple 38 | ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the 39 | returned output will contain output or error messages. A trailing newline is 40 | stripped from the output. The exit status for the command can be interpreted 41 | according to the rules for the C function :cfunc:`wait`. 42 | 43 | 44 | .. function:: getoutput(cmd) 45 | 46 | Like :func:`getstatusoutput`, except the exit status is ignored and the return 47 | value is a string containing the command's output. 48 | 49 | 50 | .. function:: getstatus(file) 51 | 52 | Return the output of ``ls -ld file`` as a string. This function uses the 53 | :func:`getoutput` function, and properly escapes backslashes and dollar signs in 54 | the argument. 55 | 56 | .. deprecated:: 2.6 57 | This function is nonobvious and useless. The name is also misleading in the 58 | presence of :func:`getstatusoutput`. 59 | 60 | 61 | Example:: 62 | 63 | >>> import commands 64 | >>> commands.getstatusoutput('ls /bin/ls') 65 | (0, '/bin/ls') 66 | >>> commands.getstatusoutput('cat /bin/junk') 67 | (256, 'cat: /bin/junk: No such file or directory') 68 | >>> commands.getstatusoutput('/bin/junk') 69 | (256, 'sh: /bin/junk: not found') 70 | >>> commands.getoutput('ls /bin/ls') 71 | '/bin/ls' 72 | >>> commands.getstatus('/bin/ls') 73 | '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls' 74 | 75 | 76 | .. seealso:: 77 | 78 | Module :mod:`subprocess` 79 | Module for spawning and managing subprocesses. 80 | 81 | -------------------------------------------------------------------------------- /library/constants.rst: -------------------------------------------------------------------------------- 1 | Built-in Constants 2 | ================== 3 | 4 | A small number of constants live in the built-in namespace. They are: 5 | 6 | .. data:: False 7 | 8 | The false value of the :class:`bool` type. 9 | 10 | .. versionadded:: 2.3 11 | 12 | 13 | .. data:: True 14 | 15 | The true value of the :class:`bool` type. 16 | 17 | .. versionadded:: 2.3 18 | 19 | 20 | .. data:: None 21 | 22 | The sole value of :attr:`types.NoneType`. ``None`` is frequently used to 23 | represent the absence of a value, as when default arguments are not passed to a 24 | function. 25 | 26 | .. versionchanged:: 2.4 27 | Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`. 28 | 29 | 30 | .. data:: NotImplemented 31 | 32 | Special value which can be returned by the "rich comparison" special methods 33 | (:meth:`__eq__`, :meth:`__lt__`, and friends), to indicate that the comparison 34 | is not implemented with respect to the other type. 35 | 36 | 37 | .. data:: Ellipsis 38 | 39 | Special value used in conjunction with extended slicing syntax. 40 | 41 | 42 | .. data:: __debug__ 43 | 44 | This constant is true if Python was not started with an :option:`-O` option. 45 | See also the :keyword:`assert` statement. 46 | 47 | 48 | .. note:: 49 | 50 | The names :data:`None` and :data:`__debug__` cannot be reassigned 51 | (assignments to them, even as an attribute name, raise :exc:`SyntaxError`), 52 | so they can be considered "true" constants. 53 | 54 | .. versionchanged:: 2.7 55 | Assignments to ``__debug__`` as an attribute became illegal. 56 | 57 | 58 | Constants added by the :mod:`site` module 59 | ----------------------------------------- 60 | 61 | The :mod:`site` module (which is imported automatically during startup, except 62 | if the :option:`-S` command-line option is given) adds several constants to the 63 | built-in namespace. They are useful for the interactive interpreter shell and 64 | should not be used in programs. 65 | 66 | .. data:: quit([code=None]) 67 | exit([code=None]) 68 | 69 | Objects that when printed, print a message like "Use quit() or Ctrl-D 70 | (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the 71 | specified exit code. 72 | 73 | .. data:: copyright 74 | license 75 | credits 76 | 77 | Objects that when printed, print a message like "Type license() to see the 78 | full license text", and when called, display the corresponding text in a 79 | pager-like fashion (one screen at a time). 80 | -------------------------------------------------------------------------------- /library/copy_reg.rst: -------------------------------------------------------------------------------- 1 | :mod:`copy_reg` --- Register :mod:`pickle` support functions 2 | ============================================================ 3 | 4 | .. module:: copy_reg 5 | :synopsis: Register pickle support functions. 6 | 7 | .. note:: 8 | The :mod:`copy_reg` module has been renamed to :mod:`copyreg` in Python 3.0. 9 | The :term:`2to3` tool will automatically adapt imports when converting your 10 | sources to 3.0. 11 | 12 | .. index:: 13 | module: pickle 14 | module: cPickle 15 | module: copy 16 | 17 | The :mod:`copy_reg` module provides support for the :mod:`pickle` and 18 | :mod:`cPickle` modules. The :mod:`copy` module is likely to use this in the 19 | future as well. It provides configuration information about object constructors 20 | which are not classes. Such constructors may be factory functions or class 21 | instances. 22 | 23 | 24 | .. function:: constructor(object) 25 | 26 | Declares *object* to be a valid constructor. If *object* is not callable (and 27 | hence not valid as a constructor), raises :exc:`TypeError`. 28 | 29 | 30 | .. function:: pickle(type, function[, constructor]) 31 | 32 | Declares that *function* should be used as a "reduction" function for objects of 33 | type *type*; *type* must not be a "classic" class object. (Classic classes are 34 | handled differently; see the documentation for the :mod:`pickle` module for 35 | details.) *function* should return either a string or a tuple containing two or 36 | three elements. 37 | 38 | The optional *constructor* parameter, if provided, is a callable object which 39 | can be used to reconstruct the object when called with the tuple of arguments 40 | returned by *function* at pickling time. :exc:`TypeError` will be raised if 41 | *object* is a class or *constructor* is not callable. 42 | 43 | See the :mod:`pickle` module for more details on the interface expected of 44 | *function* and *constructor*. 45 | 46 | -------------------------------------------------------------------------------- /library/crypt.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`crypt` --- Function to check Unix passwords 3 | ================================================= 4 | 5 | .. module:: crypt 6 | :platform: Unix 7 | :synopsis: The crypt() function used to check Unix passwords. 8 | .. moduleauthor:: Steven D. Majewski 9 | .. sectionauthor:: Steven D. Majewski 10 | .. sectionauthor:: Peter Funk 11 | 12 | 13 | .. index:: 14 | single: crypt(3) 15 | pair: cipher; DES 16 | 17 | This module implements an interface to the :manpage:`crypt(3)` routine, which is 18 | a one-way hash function based upon a modified DES algorithm; see the Unix man 19 | page for further details. Possible uses include allowing Python scripts to 20 | accept typed passwords from the user, or attempting to crack Unix passwords with 21 | a dictionary. 22 | 23 | .. index:: single: crypt(3) 24 | 25 | Notice that the behavior of this module depends on the actual implementation of 26 | the :manpage:`crypt(3)` routine in the running system. Therefore, any 27 | extensions available on the current implementation will also be available on 28 | this module. 29 | 30 | 31 | .. function:: crypt(word, salt) 32 | 33 | *word* will usually be a user's password as typed at a prompt or in a graphical 34 | interface. *salt* is usually a random two-character string which will be used 35 | to perturb the DES algorithm in one of 4096 ways. The characters in *salt* must 36 | be in the set ``[./a-zA-Z0-9]``. Returns the hashed password as a string, which 37 | will be composed of characters from the same alphabet as the salt (the first two 38 | characters represent the salt itself). 39 | 40 | .. index:: single: crypt(3) 41 | 42 | Since a few :manpage:`crypt(3)` extensions allow different values, with 43 | different sizes in the *salt*, it is recommended to use the full crypted 44 | password as salt when checking for a password. 45 | 46 | A simple example illustrating typical use:: 47 | 48 | import crypt, getpass, pwd 49 | 50 | def login(): 51 | username = raw_input('Python login:') 52 | cryptedpasswd = pwd.getpwnam(username)[1] 53 | if cryptedpasswd: 54 | if cryptedpasswd == 'x' or cryptedpasswd == '*': 55 | raise NotImplementedError( 56 | "Sorry, currently no support for shadow passwords") 57 | cleartext = getpass.getpass() 58 | return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd 59 | else: 60 | return 1 61 | 62 | -------------------------------------------------------------------------------- /library/crypto.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _crypto: 3 | 4 | ********************** 5 | Cryptographic Services 6 | ********************** 7 | 8 | .. index:: single: cryptography 9 | 10 | The modules described in this chapter implement various algorithms of a 11 | cryptographic nature. They are available at the discretion of the installation. 12 | Here's an overview: 13 | 14 | 15 | .. toctree:: 16 | 17 | hashlib.rst 18 | hmac.rst 19 | md5.rst 20 | sha.rst 21 | .. index:: 22 | pair: AES; algorithm 23 | single: cryptography 24 | single: Kuchling, Andrew 25 | 26 | Hardcore cypherpunks will probably find the cryptographic modules written by 27 | A.M. Kuchling of further interest; the package contains modules for various 28 | encryption algorithms, most notably AES. These modules are not distributed with 29 | Python but available separately. See the URL 30 | http://www.amk.ca/python/code/crypto.html for more information. 31 | 32 | -------------------------------------------------------------------------------- /library/custominterp.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _custominterp: 3 | 4 | ************************** 5 | Custom Python Interpreters 6 | ************************** 7 | 8 | The modules described in this chapter allow writing interfaces similar to 9 | Python's interactive interpreter. If you want a Python interpreter that 10 | supports some special feature in addition to the Python language, you should 11 | look at the :mod:`code` module. (The :mod:`codeop` module is lower-level, used 12 | to support compiling a possibly-incomplete chunk of Python code.) 13 | 14 | The full list of modules described in this chapter is: 15 | 16 | 17 | .. toctree:: 18 | 19 | code.rst 20 | codeop.rst 21 | -------------------------------------------------------------------------------- /library/datatypes.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _datatypes: 3 | 4 | ********** 5 | Data Types 6 | ********** 7 | 8 | The modules described in this chapter provide a variety of specialized data 9 | types such as dates and times, fixed-type arrays, heap queues, synchronized 10 | queues, and sets. 11 | 12 | Python also provides some built-in data types, in particular, 13 | :class:`dict`, :class:`list`, :class:`set` (which along with 14 | :class:`frozenset`, replaces the deprecated :mod:`sets` module), and 15 | :class:`tuple`. The :class:`str` class can be used to handle binary data 16 | and 8-bit text, and the :class:`unicode` class to handle Unicode text. 17 | 18 | The following modules are documented in this chapter: 19 | 20 | 21 | .. toctree:: 22 | 23 | datetime.rst 24 | calendar.rst 25 | collections.rst 26 | heapq.rst 27 | bisect.rst 28 | array.rst 29 | sets.rst 30 | sched.rst 31 | mutex.rst 32 | queue.rst 33 | weakref.rst 34 | userdict.rst 35 | types.rst 36 | new.rst 37 | copy.rst 38 | pprint.rst 39 | repr.rst 40 | -------------------------------------------------------------------------------- /library/debug.rst: -------------------------------------------------------------------------------- 1 | *********************** 2 | Debugging and Profiling 3 | *********************** 4 | 5 | These libraries help you with Python development: the debugger enables you to 6 | step through code, analyze stack frames and set breakpoints etc., and the 7 | profilers run code and give you a detailed breakdown of execution times, 8 | allowing you to identify bottlenecks in your programs. 9 | 10 | .. toctree:: 11 | 12 | bdb.rst 13 | pdb.rst 14 | profile.rst 15 | hotshot.rst 16 | timeit.rst 17 | trace.rst -------------------------------------------------------------------------------- /library/development.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _development: 3 | 4 | ***************** 5 | Development Tools 6 | ***************** 7 | 8 | The modules described in this chapter help you write software. For example, the 9 | :mod:`pydoc` module takes a module and generates documentation based on the 10 | module's contents. The :mod:`doctest` and :mod:`unittest` modules contains 11 | frameworks for writing unit tests that automatically exercise code and verify 12 | that the expected output is produced. :program:`2to3` can translate Python 2.x 13 | source code into valid Python 3.x code. 14 | 15 | The list of modules described in this chapter is: 16 | 17 | 18 | .. toctree:: 19 | 20 | pydoc.rst 21 | doctest.rst 22 | unittest.rst 23 | 2to3.rst 24 | test.rst 25 | -------------------------------------------------------------------------------- /library/dircache.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`dircache` --- Cached directory listings 3 | ============================================= 4 | 5 | .. module:: dircache 6 | :synopsis: Return directory listing, with cache mechanism. 7 | :deprecated: 8 | 9 | .. deprecated:: 2.6 10 | The :mod:`dircache` module has been removed in Python 3.0. 11 | 12 | 13 | .. sectionauthor:: Moshe Zadka 14 | 15 | 16 | The :mod:`dircache` module defines a function for reading directory listing 17 | using a cache, and cache invalidation using the *mtime* of the directory. 18 | Additionally, it defines a function to annotate directories by appending a 19 | slash. 20 | 21 | The :mod:`dircache` module defines the following functions: 22 | 23 | 24 | .. function:: reset() 25 | 26 | Resets the directory cache. 27 | 28 | 29 | .. function:: listdir(path) 30 | 31 | Return a directory listing of *path*, as gotten from :func:`os.listdir`. Note 32 | that unless *path* changes, further call to :func:`listdir` will not re-read the 33 | directory structure. 34 | 35 | Note that the list returned should be regarded as read-only. (Perhaps a future 36 | version should change it to return a tuple?) 37 | 38 | 39 | .. function:: opendir(path) 40 | 41 | Same as :func:`listdir`. Defined for backwards compatibility. 42 | 43 | 44 | .. function:: annotate(head, list) 45 | 46 | Assume *list* is a list of paths relative to *head*, and append, in place, a 47 | ``'/'`` to each path which points to a directory. 48 | 49 | :: 50 | 51 | >>> import dircache 52 | >>> a = dircache.listdir('/') 53 | >>> a = a[:] # Copy the return value so we can change 'a' 54 | >>> a 55 | ['bin', 'boot', 'cdrom', 'dev', 'etc', 'floppy', 'home', 'initrd', 'lib', 'lost+ 56 | found', 'mnt', 'proc', 'root', 'sbin', 'tmp', 'usr', 'var', 'vmlinuz'] 57 | >>> dircache.annotate('/', a) 58 | >>> a 59 | ['bin/', 'boot/', 'cdrom/', 'dev/', 'etc/', 'floppy/', 'home/', 'initrd/', 'lib/ 60 | ', 'lost+found/', 'mnt/', 'proc/', 'root/', 'sbin/', 'tmp/', 'usr/', 'var/', 'vm 61 | linuz'] 62 | 63 | -------------------------------------------------------------------------------- /library/distutils.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`distutils` --- Building and installing Python modules 3 | =========================================================== 4 | 5 | .. module:: distutils 6 | :synopsis: Support for building and installing Python modules into an existing Python 7 | installation. 8 | .. sectionauthor:: Fred L. Drake, Jr. 9 | 10 | 11 | The :mod:`distutils` package provides support for building and installing 12 | additional modules into a Python installation. The new modules may be either 13 | 100%-pure Python, or may be extension modules written in C, or may be 14 | collections of Python packages which include modules coded in both Python and C. 15 | 16 | This package is discussed in two separate chapters: 17 | 18 | 19 | .. seealso:: 20 | 21 | :ref:`distutils-index` 22 | The manual for developers and packagers of Python modules. This describes how 23 | to prepare :mod:`distutils`\ -based packages so that they may be easily 24 | installed into an existing Python installation. 25 | 26 | :ref:`install-index` 27 | An "administrators" manual which includes information on installing modules into 28 | an existing Python installation. You do not need to be a Python programmer to 29 | read this manual. 30 | 31 | -------------------------------------------------------------------------------- /library/dumbdbm.rst: -------------------------------------------------------------------------------- 1 | :mod:`dumbdbm` --- Portable DBM implementation 2 | ============================================== 3 | 4 | .. module:: dumbdbm 5 | :synopsis: Portable implementation of the simple DBM interface. 6 | 7 | .. note:: 8 | The :mod:`dumbdbm` module has been renamed to :mod:`dbm.dumb` in Python 3.0. 9 | The :term:`2to3` tool will automatically adapt imports when converting your 10 | sources to 3.0. 11 | 12 | .. index:: single: databases 13 | 14 | .. note:: 15 | 16 | The :mod:`dumbdbm` module is intended as a last resort fallback for the 17 | :mod:`anydbm` module when no more robust module is available. The :mod:`dumbdbm` 18 | module is not written for speed and is not nearly as heavily used as the other 19 | database modules. 20 | 21 | The :mod:`dumbdbm` module provides a persistent dictionary-like interface which 22 | is written entirely in Python. Unlike other modules such as :mod:`gdbm` and 23 | :mod:`bsddb`, no external library is required. As with other persistent 24 | mappings, the keys and values must always be strings. 25 | 26 | The module defines the following: 27 | 28 | 29 | .. exception:: error 30 | 31 | Raised on dumbdbm-specific errors, such as I/O errors. :exc:`KeyError` is 32 | raised for general mapping errors like specifying an incorrect key. 33 | 34 | 35 | .. function:: open(filename[, flag[, mode]]) 36 | 37 | Open a dumbdbm database and return a dumbdbm object. The *filename* argument is 38 | the basename of the database file (without any specific extensions). When a 39 | dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions 40 | are created. 41 | 42 | The optional *flag* argument is currently ignored; the database is always opened 43 | for update, and will be created if it does not exist. 44 | 45 | The optional *mode* argument is the Unix mode of the file, used only when the 46 | database has to be created. It defaults to octal ``0666`` (and will be modified 47 | by the prevailing umask). 48 | 49 | .. versionchanged:: 2.2 50 | The *mode* argument was ignored in earlier versions. 51 | 52 | 53 | .. seealso:: 54 | 55 | Module :mod:`anydbm` 56 | Generic interface to ``dbm``\ -style databases. 57 | 58 | Module :mod:`dbm` 59 | Similar interface to the DBM/NDBM library. 60 | 61 | Module :mod:`gdbm` 62 | Similar interface to the GNU GDBM library. 63 | 64 | Module :mod:`shelve` 65 | Persistence module which stores non-string data. 66 | 67 | Module :mod:`whichdb` 68 | Utility module used to determine the type of an existing database. 69 | 70 | 71 | .. _dumbdbm-objects: 72 | 73 | Dumbdbm Objects 74 | --------------- 75 | 76 | In addition to the methods provided by the :class:`UserDict.DictMixin` class, 77 | :class:`dumbdbm` objects provide the following methods. 78 | 79 | 80 | .. method:: dumbdbm.sync() 81 | 82 | Synchronize the on-disk directory and data files. This method is called by the 83 | :meth:`sync` method of :class:`Shelve` objects. 84 | 85 | -------------------------------------------------------------------------------- /library/dummy_thread.rst: -------------------------------------------------------------------------------- 1 | :mod:`dummy_thread` --- Drop-in replacement for the :mod:`thread` module 2 | ======================================================================== 3 | 4 | .. module:: dummy_thread 5 | :synopsis: Drop-in replacement for the thread module. 6 | 7 | .. note:: 8 | The :mod:`dummy_thread` module has been renamed to :mod:`_dummy_thread` in 9 | Python 3.0. The :term:`2to3` tool will automatically adapt imports when 10 | converting your sources to 3.0; however, you should consider using the 11 | high-lever :mod:`dummy_threading` module instead. 12 | 13 | 14 | This module provides a duplicate interface to the :mod:`thread` module. It is 15 | meant to be imported when the :mod:`thread` module is not provided on a 16 | platform. 17 | 18 | Suggested usage is:: 19 | 20 | try: 21 | import thread as _thread 22 | except ImportError: 23 | import dummy_thread as _thread 24 | 25 | Be careful to not use this module where deadlock might occur from a thread 26 | being created that blocks waiting for another thread to be created. This often 27 | occurs with blocking I/O. 28 | 29 | -------------------------------------------------------------------------------- /library/dummy_threading.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module 3 | ============================================================================== 4 | 5 | .. module:: dummy_threading 6 | :synopsis: Drop-in replacement for the threading module. 7 | 8 | 9 | This module provides a duplicate interface to the :mod:`threading` module. It 10 | is meant to be imported when the :mod:`thread` module is not provided on a 11 | platform. 12 | 13 | Suggested usage is:: 14 | 15 | try: 16 | import threading as _threading 17 | except ImportError: 18 | import dummy_threading as _threading 19 | 20 | Be careful to not use this module where deadlock might occur from a thread 21 | being created that blocks waiting for another thread to be created. This often 22 | occurs with blocking I/O. 23 | 24 | -------------------------------------------------------------------------------- /library/email-examples.rst: -------------------------------------------------------------------------------- 1 | .. _email-examples: 2 | 3 | :mod:`email`: Examples 4 | ---------------------- 5 | 6 | Here are a few examples of how to use the :mod:`email` package to read, write, 7 | and send simple email messages, as well as more complex MIME messages. 8 | 9 | First, let's see how to create and send a simple text message: 10 | 11 | .. literalinclude:: ../includes/email-simple.py 12 | 13 | 14 | And parsing RFC822 headers can easily be done by the parse(filename) or 15 | parsestr(message_as_string) methods of the Parser() class: 16 | 17 | .. literalinclude:: ../includes/email-headers.py 18 | 19 | 20 | Here's an example of how to send a MIME message containing a bunch of family 21 | pictures that may be residing in a directory: 22 | 23 | .. literalinclude:: ../includes/email-mime.py 24 | 25 | 26 | Here's an example of how to send the entire contents of a directory as an email 27 | message: [1]_ 28 | 29 | .. literalinclude:: ../includes/email-dir.py 30 | 31 | 32 | Here's an example of how to unpack a MIME message like the one 33 | above, into a directory of files: 34 | 35 | .. literalinclude:: ../includes/email-unpack.py 36 | 37 | Here's an example of how to create an HTML message with an alternative plain 38 | text version: [2]_ 39 | 40 | .. literalinclude:: ../includes/email-alternative.py 41 | 42 | 43 | .. rubric:: Footnotes 44 | 45 | .. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples. 46 | .. [2] Contributed by Martin Matejek. 47 | -------------------------------------------------------------------------------- /library/email.encoders.rst: -------------------------------------------------------------------------------- 1 | :mod:`email`: Encoders 2 | ---------------------- 3 | 4 | .. module:: email.encoders 5 | :synopsis: Encoders for email message payloads. 6 | 7 | 8 | When creating :class:`~email.message.Message` objects from scratch, you often 9 | need to encode the payloads for transport through compliant mail servers. This 10 | is especially true for :mimetype:`image/\*` and :mimetype:`text/\*` type messages 11 | containing binary data. 12 | 13 | The :mod:`email` package provides some convenient encodings in its 14 | :mod:`encoders` module. These encoders are actually used by the 15 | :class:`~email.mime.audio.MIMEAudio` and :class:`~email.mime.image.MIMEImage` 16 | class constructors to provide default encodings. All encoder functions take 17 | exactly one argument, the message object to encode. They usually extract the 18 | payload, encode it, and reset the payload to this newly encoded value. They 19 | should also set the :mailheader:`Content-Transfer-Encoding` header as appropriate. 20 | 21 | Here are the encoding functions provided: 22 | 23 | 24 | .. function:: encode_quopri(msg) 25 | 26 | Encodes the payload into quoted-printable form and sets the 27 | :mailheader:`Content-Transfer-Encoding` header to ``quoted-printable`` [#]_. 28 | This is a good encoding to use when most of your payload is normal printable 29 | data, but contains a few unprintable characters. 30 | 31 | 32 | .. function:: encode_base64(msg) 33 | 34 | Encodes the payload into base64 form and sets the 35 | :mailheader:`Content-Transfer-Encoding` header to ``base64``. This is a good 36 | encoding to use when most of your payload is unprintable data since it is a more 37 | compact form than quoted-printable. The drawback of base64 encoding is that it 38 | renders the text non-human readable. 39 | 40 | 41 | .. function:: encode_7or8bit(msg) 42 | 43 | This doesn't actually modify the message's payload, but it does set the 44 | :mailheader:`Content-Transfer-Encoding` header to either ``7bit`` or ``8bit`` as 45 | appropriate, based on the payload data. 46 | 47 | 48 | .. function:: encode_noop(msg) 49 | 50 | This does nothing; it doesn't even set the 51 | :mailheader:`Content-Transfer-Encoding` header. 52 | 53 | .. rubric:: Footnotes 54 | 55 | .. [#] Note that encoding with :meth:`encode_quopri` also encodes all tabs and space 56 | characters in the data. 57 | 58 | -------------------------------------------------------------------------------- /library/email.iterators.rst: -------------------------------------------------------------------------------- 1 | :mod:`email`: Iterators 2 | ----------------------- 3 | 4 | .. module:: email.iterators 5 | :synopsis: Iterate over a message object tree. 6 | 7 | 8 | Iterating over a message object tree is fairly easy with the 9 | :meth:`Message.walk` method. The :mod:`email.iterators` module provides some 10 | useful higher level iterations over message object trees. 11 | 12 | 13 | .. function:: body_line_iterator(msg[, decode]) 14 | 15 | This iterates over all the payloads in all the subparts of *msg*, returning the 16 | string payloads line-by-line. It skips over all the subpart headers, and it 17 | skips over any subpart with a payload that isn't a Python string. This is 18 | somewhat equivalent to reading the flat text representation of the message from 19 | a file using :meth:`readline`, skipping over all the intervening headers. 20 | 21 | Optional *decode* is passed through to :meth:`Message.get_payload`. 22 | 23 | 24 | .. function:: typed_subpart_iterator(msg[, maintype[, subtype]]) 25 | 26 | This iterates over all the subparts of *msg*, returning only those subparts that 27 | match the MIME type specified by *maintype* and *subtype*. 28 | 29 | Note that *subtype* is optional; if omitted, then subpart MIME type matching is 30 | done only with the main type. *maintype* is optional too; it defaults to 31 | :mimetype:`text`. 32 | 33 | Thus, by default :func:`typed_subpart_iterator` returns each subpart that has a 34 | MIME type of :mimetype:`text/\*`. 35 | 36 | The following function has been added as a useful debugging tool. It should 37 | *not* be considered part of the supported public interface for the package. 38 | 39 | 40 | .. function:: _structure(msg[, fp[, level]]) 41 | 42 | Prints an indented representation of the content types of the message object 43 | structure. For example:: 44 | 45 | >>> msg = email.message_from_file(somefile) 46 | >>> _structure(msg) 47 | multipart/mixed 48 | text/plain 49 | text/plain 50 | multipart/digest 51 | message/rfc822 52 | text/plain 53 | message/rfc822 54 | text/plain 55 | message/rfc822 56 | text/plain 57 | message/rfc822 58 | text/plain 59 | message/rfc822 60 | text/plain 61 | text/plain 62 | 63 | Optional *fp* is a file-like object to print the output to. It must be suitable 64 | for Python's extended print statement. *level* is used internally. 65 | 66 | -------------------------------------------------------------------------------- /library/fileformats.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _fileformats: 3 | 4 | ************ 5 | File Formats 6 | ************ 7 | 8 | The modules described in this chapter parse various miscellaneous file formats 9 | that aren't markup languages or are related to e-mail. 10 | 11 | 12 | .. toctree:: 13 | 14 | csv.rst 15 | configparser.rst 16 | robotparser.rst 17 | netrc.rst 18 | xdrlib.rst 19 | plistlib.rst 20 | -------------------------------------------------------------------------------- /library/filesys.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _filesys: 3 | 4 | ************************* 5 | File and Directory Access 6 | ************************* 7 | 8 | The modules described in this chapter deal with disk files and directories. For 9 | example, there are modules for reading the properties of files, manipulating 10 | paths in a portable way, and creating temporary files. The full list of modules 11 | in this chapter is: 12 | 13 | 14 | .. toctree:: 15 | 16 | os.path.rst 17 | fileinput.rst 18 | stat.rst 19 | statvfs.rst 20 | filecmp.rst 21 | tempfile.rst 22 | glob.rst 23 | fnmatch.rst 24 | linecache.rst 25 | shutil.rst 26 | dircache.rst 27 | macpath.rst 28 | 29 | 30 | .. seealso:: 31 | 32 | Section :ref:`bltin-file-objects` 33 | A description of Python's built-in file objects. 34 | 35 | Module :mod:`os` 36 | Operating system interfaces, including functions to work with files at a lower 37 | level than the built-in file object. 38 | 39 | -------------------------------------------------------------------------------- /library/fpformat.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`fpformat` --- Floating point conversions 3 | ============================================== 4 | 5 | .. module:: fpformat 6 | :synopsis: General floating point formatting functions. 7 | :deprecated: 8 | 9 | .. deprecated:: 2.6 10 | The :mod:`fpformat` module has been removed in Python 3.0. 11 | 12 | .. sectionauthor:: Moshe Zadka 13 | 14 | 15 | The :mod:`fpformat` module defines functions for dealing with floating point 16 | numbers representations in 100% pure Python. 17 | 18 | .. note:: 19 | 20 | This module is unnecessary: everything here can be done using the ``%`` string 21 | interpolation operator described in the :ref:`string-formatting` section. 22 | 23 | The :mod:`fpformat` module defines the following functions and an exception: 24 | 25 | 26 | .. function:: fix(x, digs) 27 | 28 | Format *x* as ``[-]ddd.ddd`` with *digs* digits after the point and at least one 29 | digit before. If ``digs <= 0``, the decimal point is suppressed. 30 | 31 | *x* can be either a number or a string that looks like one. *digs* is an 32 | integer. 33 | 34 | Return value is a string. 35 | 36 | 37 | .. function:: sci(x, digs) 38 | 39 | Format *x* as ``[-]d.dddE[+-]ddd`` with *digs* digits after the point and 40 | exactly one digit before. If ``digs <= 0``, one digit is kept and the point is 41 | suppressed. 42 | 43 | *x* can be either a real number, or a string that looks like one. *digs* is an 44 | integer. 45 | 46 | Return value is a string. 47 | 48 | 49 | .. exception:: NotANumber 50 | 51 | Exception raised when a string passed to :func:`fix` or :func:`sci` as the *x* 52 | parameter does not look like a number. This is a subclass of :exc:`ValueError` 53 | when the standard exceptions are strings. The exception value is the improperly 54 | formatted string that caused the exception to be raised. 55 | 56 | Example:: 57 | 58 | >>> import fpformat 59 | >>> fpformat.fix(1.23, 1) 60 | '1.2' 61 | 62 | -------------------------------------------------------------------------------- /library/frameworks.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _frameworks: 3 | 4 | ****************** 5 | Program Frameworks 6 | ****************** 7 | 8 | The modules described in this chapter are frameworks that will largely dictate 9 | the structure of your program. Currently the modules described here are all 10 | oriented toward writing command-line interfaces. 11 | 12 | The full list of modules described in this chapter is: 13 | 14 | 15 | .. toctree:: 16 | 17 | cmd.rst 18 | shlex.rst 19 | -------------------------------------------------------------------------------- /library/future_builtins.rst: -------------------------------------------------------------------------------- 1 | :mod:`future_builtins` --- Python 3 builtins 2 | ============================================ 3 | 4 | .. module:: future_builtins 5 | .. sectionauthor:: Georg Brandl 6 | .. versionadded:: 2.6 7 | 8 | This module provides functions that exist in 2.x, but have different behavior in 9 | Python 3, so they cannot be put into the 2.x builtins namespace. 10 | 11 | Instead, if you want to write code compatible with Python 3 builtins, import 12 | them from this module, like this:: 13 | 14 | from future_builtins import map, filter 15 | 16 | ... code using Python 3-style map and filter ... 17 | 18 | The :term:`2to3` tool that ports Python 2 code to Python 3 will recognize 19 | this usage and leave the new builtins alone. 20 | 21 | .. note:: 22 | 23 | The Python 3 :func:`print` function is already in the builtins, but cannot be 24 | accessed from Python 2 code unless you use the appropriate future statement:: 25 | 26 | from __future__ import print_function 27 | 28 | 29 | Available builtins are: 30 | 31 | .. function:: ascii(object) 32 | 33 | Returns the same as :func:`repr`. In Python 3, :func:`repr` will return 34 | printable Unicode characters unescaped, while :func:`ascii` will always 35 | backslash-escape them. Using :func:`future_builtins.ascii` instead of 36 | :func:`repr` in 2.6 code makes it clear that you need a pure ASCII return 37 | value. 38 | 39 | .. function:: filter(function, iterable) 40 | 41 | Works like :func:`itertools.ifilter`. 42 | 43 | .. function:: hex(object) 44 | 45 | Works like the built-in :func:`hex`, but instead of :meth:`__hex__` it will 46 | use the :meth:`__index__` method on its argument to get an integer that is 47 | then converted to hexadecimal. 48 | 49 | .. function:: map(function, iterable, ...) 50 | 51 | Works like :func:`itertools.imap`. 52 | 53 | .. function:: oct(object) 54 | 55 | Works like the built-in :func:`oct`, but instead of :meth:`__oct__` it will 56 | use the :meth:`__index__` method on its argument to get an integer that is 57 | then converted to octal. 58 | 59 | .. function:: zip(*iterables) 60 | 61 | Works like :func:`itertools.izip`. 62 | -------------------------------------------------------------------------------- /library/getpass.rst: -------------------------------------------------------------------------------- 1 | :mod:`getpass` --- Portable password input 2 | ========================================== 3 | 4 | .. module:: getpass 5 | :synopsis: Portable reading of passwords and retrieval of the userid. 6 | .. moduleauthor:: Piers Lauder 7 | .. sectionauthor:: Fred L. Drake, Jr. 8 | .. Windows (& Mac?) support by Guido van Rossum. 9 | 10 | The :mod:`getpass` module provides two functions: 11 | 12 | 13 | .. function:: getpass([prompt[, stream]]) 14 | 15 | Prompt the user for a password without echoing. The user is prompted using the 16 | string *prompt*, which defaults to ``'Password: '``. On Unix, the prompt is 17 | written to the file-like object *stream*. *stream* defaults to the 18 | controlling terminal (/dev/tty) or if that is unavailable to ``sys.stderr`` 19 | (this argument is ignored on Windows). 20 | 21 | If echo free input is unavailable getpass() falls back to printing 22 | a warning message to *stream* and reading from ``sys.stdin`` and 23 | issuing a :exc:`GetPassWarning`. 24 | 25 | Availability: Macintosh, Unix, Windows. 26 | 27 | .. versionchanged:: 2.5 28 | The *stream* parameter was added. 29 | .. versionchanged:: 2.6 30 | On Unix it defaults to using /dev/tty before falling back 31 | to ``sys.stdin`` and ``sys.stderr``. 32 | .. note:: 33 | If you call getpass from within IDLE, the input may be done in the 34 | terminal you launched IDLE from rather than the idle window itself. 35 | 36 | 37 | .. exception:: GetPassWarning 38 | 39 | A :exc:`UserWarning` subclass issued when password input may be echoed. 40 | 41 | 42 | .. function:: getuser() 43 | 44 | Return the "login name" of the user. Availability: Unix, Windows. 45 | 46 | This function checks the environment variables :envvar:`LOGNAME`, 47 | :envvar:`USER`, :envvar:`LNAME` and :envvar:`USERNAME`, in order, and returns 48 | the value of the first one which is set to a non-empty string. If none are set, 49 | the login name from the password database is returned on systems which support 50 | the :mod:`pwd` module, otherwise, an exception is raised. 51 | 52 | -------------------------------------------------------------------------------- /library/glob.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`glob` --- Unix style pathname pattern expansion 3 | ===================================================== 4 | 5 | .. module:: glob 6 | :synopsis: Unix shell style pathname pattern expansion. 7 | 8 | 9 | .. index:: single: filenames; pathname expansion 10 | 11 | The :mod:`glob` module finds all the pathnames matching a specified pattern 12 | according to the rules used by the Unix shell. No tilde expansion is done, but 13 | ``*``, ``?``, and character ranges expressed with ``[]`` will be correctly 14 | matched. This is done by using the :func:`os.listdir` and 15 | :func:`fnmatch.fnmatch` functions in concert, and not by actually invoking a 16 | subshell. (For tilde and shell variable expansion, use 17 | :func:`os.path.expanduser` and :func:`os.path.expandvars`.) 18 | 19 | .. seealso:: 20 | 21 | Latest version of the `glob module Python source code 22 | `_ 23 | 24 | .. function:: glob(pathname) 25 | 26 | Return a possibly-empty list of path names that match *pathname*, which must be 27 | a string containing a path specification. *pathname* can be either absolute 28 | (like :file:`/usr/src/Python-1.5/Makefile`) or relative (like 29 | :file:`../../Tools/\*/\*.gif`), and can contain shell-style wildcards. Broken 30 | symlinks are included in the results (as in the shell). 31 | 32 | 33 | .. function:: iglob(pathname) 34 | 35 | Return an :term:`iterator` which yields the same values as :func:`glob` 36 | without actually storing them all simultaneously. 37 | 38 | .. versionadded:: 2.5 39 | 40 | For example, consider a directory containing only the following files: 41 | :file:`1.gif`, :file:`2.txt`, and :file:`card.gif`. :func:`glob` will produce 42 | the following results. Notice how any leading components of the path are 43 | preserved. :: 44 | 45 | >>> import glob 46 | >>> glob.glob('./[0-9].*') 47 | ['./1.gif', './2.txt'] 48 | >>> glob.glob('*.gif') 49 | ['1.gif', 'card.gif'] 50 | >>> glob.glob('?.gif') 51 | ['1.gif'] 52 | 53 | 54 | .. seealso:: 55 | 56 | Module :mod:`fnmatch` 57 | Shell-style filename (not path) expansion 58 | 59 | -------------------------------------------------------------------------------- /library/grp.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`grp` --- The group database 3 | ================================= 4 | 5 | .. module:: grp 6 | :platform: Unix 7 | :synopsis: The group database (getgrnam() and friends). 8 | 9 | 10 | This module provides access to the Unix group database. It is available on all 11 | Unix versions. 12 | 13 | Group database entries are reported as a tuple-like object, whose attributes 14 | correspond to the members of the ``group`` structure (Attribute field below, see 15 | ````): 16 | 17 | +-------+-----------+---------------------------------+ 18 | | Index | Attribute | Meaning | 19 | +=======+===========+=================================+ 20 | | 0 | gr_name | the name of the group | 21 | +-------+-----------+---------------------------------+ 22 | | 1 | gr_passwd | the (encrypted) group password; | 23 | | | | often empty | 24 | +-------+-----------+---------------------------------+ 25 | | 2 | gr_gid | the numerical group ID | 26 | +-------+-----------+---------------------------------+ 27 | | 3 | gr_mem | all the group member's user | 28 | | | | names | 29 | +-------+-----------+---------------------------------+ 30 | 31 | The gid is an integer, name and password are strings, and the member list is a 32 | list of strings. (Note that most users are not explicitly listed as members of 33 | the group they are in according to the password database. Check both databases 34 | to get complete membership information. Also note that a ``gr_name`` that 35 | starts with a ``+`` or ``-`` is likely to be a YP/NIS reference and may not be 36 | accessible via :func:`getgrnam` or :func:`getgrgid`.) 37 | 38 | It defines the following items: 39 | 40 | 41 | .. function:: getgrgid(gid) 42 | 43 | Return the group database entry for the given numeric group ID. :exc:`KeyError` 44 | is raised if the entry asked for cannot be found. 45 | 46 | 47 | .. function:: getgrnam(name) 48 | 49 | Return the group database entry for the given group name. :exc:`KeyError` is 50 | raised if the entry asked for cannot be found. 51 | 52 | 53 | .. function:: getgrall() 54 | 55 | Return a list of all available group entries, in arbitrary order. 56 | 57 | 58 | .. seealso:: 59 | 60 | Module :mod:`pwd` 61 | An interface to the user database, similar to this. 62 | 63 | Module :mod:`spwd` 64 | An interface to the shadow password database, similar to this. 65 | 66 | -------------------------------------------------------------------------------- /library/hmac.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`hmac` --- Keyed-Hashing for Message Authentication 3 | ======================================================== 4 | 5 | .. module:: hmac 6 | :synopsis: Keyed-Hashing for Message Authentication (HMAC) implementation for Python. 7 | .. moduleauthor:: Gerhard Häring 8 | .. sectionauthor:: Gerhard Häring 9 | 10 | 11 | .. versionadded:: 2.2 12 | 13 | This module implements the HMAC algorithm as described by :rfc:`2104`. 14 | 15 | 16 | .. function:: new(key[, msg[, digestmod]]) 17 | 18 | Return a new hmac object. If *msg* is present, the method call ``update(msg)`` 19 | is made. *digestmod* is the digest constructor or module for the HMAC object to 20 | use. It defaults to the :func:`hashlib.md5` constructor. 21 | 22 | 23 | An HMAC object has the following methods: 24 | 25 | 26 | .. method:: hmac.update(msg) 27 | 28 | Update the hmac object with the string *msg*. Repeated calls are equivalent to 29 | a single call with the concatenation of all the arguments: ``m.update(a); 30 | m.update(b)`` is equivalent to ``m.update(a + b)``. 31 | 32 | 33 | .. method:: hmac.digest() 34 | 35 | Return the digest of the strings passed to the :meth:`update` method so far. 36 | This string will be the same length as the *digest_size* of the digest given to 37 | the constructor. It may contain non-ASCII characters, including NUL bytes. 38 | 39 | 40 | .. method:: hmac.hexdigest() 41 | 42 | Like :meth:`digest` except the digest is returned as a string twice the length 43 | containing only hexadecimal digits. This may be used to exchange the value 44 | safely in email or other non-binary environments. 45 | 46 | 47 | .. method:: hmac.copy() 48 | 49 | Return a copy ("clone") of the hmac object. This can be used to efficiently 50 | compute the digests of strings that share a common initial substring. 51 | 52 | 53 | .. seealso:: 54 | 55 | Module :mod:`hashlib` 56 | The Python module providing secure hash functions. 57 | 58 | -------------------------------------------------------------------------------- /library/i18n.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _i18n: 3 | 4 | ******************** 5 | Internationalization 6 | ******************** 7 | 8 | The modules described in this chapter help you write software that is 9 | independent of language and locale by providing mechanisms for selecting a 10 | language to be used in program messages or by tailoring output to match local 11 | conventions. 12 | 13 | The list of modules described in this chapter is: 14 | 15 | 16 | .. toctree:: 17 | 18 | gettext.rst 19 | locale.rst 20 | -------------------------------------------------------------------------------- /library/imghdr.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`imghdr` --- Determine the type of an image 3 | ================================================ 4 | 5 | .. module:: imghdr 6 | :synopsis: Determine the type of image contained in a file or byte stream. 7 | 8 | 9 | The :mod:`imghdr` module determines the type of image contained in a file or 10 | byte stream. 11 | 12 | The :mod:`imghdr` module defines the following function: 13 | 14 | 15 | .. function:: what(filename[, h]) 16 | 17 | Tests the image data contained in the file named by *filename*, and returns a 18 | string describing the image type. If optional *h* is provided, the *filename* 19 | is ignored and *h* is assumed to contain the byte stream to test. 20 | 21 | The following image types are recognized, as listed below with the return value 22 | from :func:`what`: 23 | 24 | +------------+-----------------------------------+ 25 | | Value | Image format | 26 | +============+===================================+ 27 | | ``'rgb'`` | SGI ImgLib Files | 28 | +------------+-----------------------------------+ 29 | | ``'gif'`` | GIF 87a and 89a Files | 30 | +------------+-----------------------------------+ 31 | | ``'pbm'`` | Portable Bitmap Files | 32 | +------------+-----------------------------------+ 33 | | ``'pgm'`` | Portable Graymap Files | 34 | +------------+-----------------------------------+ 35 | | ``'ppm'`` | Portable Pixmap Files | 36 | +------------+-----------------------------------+ 37 | | ``'tiff'`` | TIFF Files | 38 | +------------+-----------------------------------+ 39 | | ``'rast'`` | Sun Raster Files | 40 | +------------+-----------------------------------+ 41 | | ``'xbm'`` | X Bitmap Files | 42 | +------------+-----------------------------------+ 43 | | ``'jpeg'`` | JPEG data in JFIF or Exif formats | 44 | +------------+-----------------------------------+ 45 | | ``'bmp'`` | BMP files | 46 | +------------+-----------------------------------+ 47 | | ``'png'`` | Portable Network Graphics | 48 | +------------+-----------------------------------+ 49 | 50 | .. versionadded:: 2.5 51 | Exif detection. 52 | 53 | You can extend the list of file types :mod:`imghdr` can recognize by appending 54 | to this variable: 55 | 56 | 57 | .. data:: tests 58 | 59 | A list of functions performing the individual tests. Each function takes two 60 | arguments: the byte-stream and an open file-like object. When :func:`what` is 61 | called with a byte-stream, the file-like object will be ``None``. 62 | 63 | The test function should return a string describing the image type if the test 64 | succeeded, or ``None`` if it failed. 65 | 66 | Example:: 67 | 68 | >>> import imghdr 69 | >>> imghdr.what('/tmp/bass.gif') 70 | 'gif' 71 | 72 | -------------------------------------------------------------------------------- /library/importlib.rst: -------------------------------------------------------------------------------- 1 | :mod:`importlib` -- Convenience wrappers for :func:`__import__` 2 | =============================================================== 3 | 4 | .. module:: importlib 5 | :synopsis: Convenience wrappers for __import__ 6 | 7 | .. moduleauthor:: Brett Cannon 8 | .. sectionauthor:: Brett Cannon 9 | 10 | .. versionadded:: 2.7 11 | 12 | This module is a minor subset of what is available in the more full-featured 13 | package of the same name from Python 3.1 that provides a complete 14 | implementation of :keyword:`import`. What is here has been provided to 15 | help ease in transitioning from 2.7 to 3.1. 16 | 17 | 18 | .. function:: import_module(name, package=None) 19 | 20 | Import a module. The *name* argument specifies what module to 21 | import in absolute or relative terms 22 | (e.g. either ``pkg.mod`` or ``..mod``). If the name is 23 | specified in relative terms, then the *package* argument must be 24 | specified to the package which is to act as the anchor for resolving the 25 | package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import 26 | ``pkg.mod``). The specified module will be inserted into 27 | :data:`sys.modules` and returned. 28 | -------------------------------------------------------------------------------- /library/index.rst: -------------------------------------------------------------------------------- 1 | .. _library-index: 2 | 3 | ############################### 4 | The Python Standard Library 5 | ############################### 6 | 7 | :Release: |version| 8 | :Date: |today| 9 | 10 | While :ref:`reference-index` describes the exact syntax and 11 | semantics of the Python language, this library reference manual 12 | describes the standard library that is distributed with Python. It also 13 | describes some of the optional components that are commonly included 14 | in Python distributions. 15 | 16 | Python's standard library is very extensive, offering a wide range of 17 | facilities as indicated by the long table of contents listed below. The 18 | library contains built-in modules (written in C) that provide access to 19 | system functionality such as file I/O that would otherwise be 20 | inaccessible to Python programmers, as well as modules written in Python 21 | that provide standardized solutions for many problems that occur in 22 | everyday programming. Some of these modules are explicitly designed to 23 | encourage and enhance the portability of Python programs by abstracting 24 | away platform-specifics into platform-neutral APIs. 25 | 26 | The Python installers for the Windows platform usually includes 27 | the entire standard library and often also include many additional 28 | components. For Unix-like operating systems Python is normally provided 29 | as a collection of packages, so it may be necessary to use the packaging 30 | tools provided with the operating system to obtain some or all of the 31 | optional components. 32 | 33 | In addition to the standard library, there is a growing collection of 34 | several thousand components (from individual programs and modules to 35 | packages and entire application development frameworks), available from 36 | the `Python Package Index `_. 37 | 38 | 39 | .. toctree:: 40 | :maxdepth: 2 41 | :numbered: 42 | 43 | intro.rst 44 | functions.rst 45 | constants.rst 46 | stdtypes.rst 47 | exceptions.rst 48 | 49 | strings.rst 50 | datatypes.rst 51 | numeric.rst 52 | filesys.rst 53 | persistence.rst 54 | archiving.rst 55 | fileformats.rst 56 | crypto.rst 57 | allos.rst 58 | someos.rst 59 | ipc.rst 60 | netdata.rst 61 | markup.rst 62 | internet.rst 63 | mm.rst 64 | i18n.rst 65 | frameworks.rst 66 | tk.rst 67 | development.rst 68 | debug.rst 69 | python.rst 70 | custominterp.rst 71 | restricted.rst 72 | modules.rst 73 | language.rst 74 | compiler.rst 75 | misc.rst 76 | windows.rst 77 | unix.rst 78 | mac.rst 79 | macosa.rst 80 | sgi.rst 81 | sun.rst 82 | undoc.rst 83 | -------------------------------------------------------------------------------- /library/internet.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _internet: 3 | 4 | ****************************** 5 | Internet Protocols and Support 6 | ****************************** 7 | 8 | .. index:: 9 | single: WWW 10 | single: Internet 11 | single: World Wide Web 12 | 13 | .. index:: module: socket 14 | 15 | The modules described in this chapter implement Internet protocols and support 16 | for related technology. They are all implemented in Python. Most of these 17 | modules require the presence of the system-dependent module :mod:`socket`, which 18 | is currently supported on most popular platforms. Here is an overview: 19 | 20 | 21 | .. toctree:: 22 | 23 | webbrowser.rst 24 | cgi.rst 25 | cgitb.rst 26 | wsgiref.rst 27 | urllib.rst 28 | urllib2.rst 29 | httplib.rst 30 | ftplib.rst 31 | poplib.rst 32 | imaplib.rst 33 | nntplib.rst 34 | smtplib.rst 35 | smtpd.rst 36 | telnetlib.rst 37 | uuid.rst 38 | urlparse.rst 39 | socketserver.rst 40 | basehttpserver.rst 41 | simplehttpserver.rst 42 | cgihttpserver.rst 43 | cookielib.rst 44 | cookie.rst 45 | xmlrpclib.rst 46 | simplexmlrpcserver.rst 47 | docxmlrpcserver.rst 48 | -------------------------------------------------------------------------------- /library/intro.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _library-intro: 3 | 4 | ************ 5 | Introduction 6 | ************ 7 | 8 | The "Python library" contains several different kinds of components. 9 | 10 | It contains data types that would normally be considered part of the "core" of a 11 | language, such as numbers and lists. For these types, the Python language core 12 | defines the form of literals and places some constraints on their semantics, but 13 | does not fully define the semantics. (On the other hand, the language core does 14 | define syntactic properties like the spelling and priorities of operators.) 15 | 16 | The library also contains built-in functions and exceptions --- objects that can 17 | be used by all Python code without the need of an :keyword:`import` statement. 18 | Some of these are defined by the core language, but many are not essential for 19 | the core semantics and are only described here. 20 | 21 | The bulk of the library, however, consists of a collection of modules. There are 22 | many ways to dissect this collection. Some modules are written in C and built 23 | in to the Python interpreter; others are written in Python and imported in 24 | source form. Some modules provide interfaces that are highly specific to 25 | Python, like printing a stack trace; some provide interfaces that are specific 26 | to particular operating systems, such as access to specific hardware; others 27 | provide interfaces that are specific to a particular application domain, like 28 | the World Wide Web. Some modules are available in all versions and ports of 29 | Python; others are only available when the underlying system supports or 30 | requires them; yet others are available only when a particular configuration 31 | option was chosen at the time when Python was compiled and installed. 32 | 33 | This manual is organized "from the inside out:" it first describes the built-in 34 | data types, then the built-in functions and exceptions, and finally the modules, 35 | grouped in chapters of related modules. The ordering of the chapters as well as 36 | the ordering of the modules within each chapter is roughly from most relevant to 37 | least important. 38 | 39 | This means that if you start reading this manual from the start, and skip to the 40 | next chapter when you get bored, you will get a reasonable overview of the 41 | available modules and application areas that are supported by the Python 42 | library. Of course, you don't *have* to read it like a novel --- you can also 43 | browse the table of contents (in front of the manual), or look for a specific 44 | function, module or term in the index (in the back). And finally, if you enjoy 45 | learning about random subjects, you choose a random page number (see module 46 | :mod:`random`) and read a section or two. Regardless of the order in which you 47 | read the sections of this manual, it helps to start with chapter 48 | :ref:`built-in-funcs`, as the remainder of the manual assumes familiarity with 49 | this material. 50 | 51 | Let the show begin! 52 | 53 | -------------------------------------------------------------------------------- /library/ipc.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _ipc: 3 | 4 | ***************************************** 5 | Interprocess Communication and Networking 6 | ***************************************** 7 | 8 | The modules described in this chapter provide mechanisms for different processes 9 | to communicate. 10 | 11 | Some modules only work for two processes that are on the same machine, e.g. 12 | :mod:`signal` and :mod:`subprocess`. Other modules support networking protocols 13 | that two or more processes can used to communicate across machines. 14 | 15 | The list of modules described in this chapter is: 16 | 17 | 18 | .. toctree:: 19 | 20 | subprocess.rst 21 | socket.rst 22 | ssl.rst 23 | signal.rst 24 | popen2.rst 25 | asyncore.rst 26 | asynchat.rst 27 | -------------------------------------------------------------------------------- /library/keyword.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`keyword` --- Testing for Python keywords 3 | ============================================== 4 | 5 | .. module:: keyword 6 | :synopsis: Test whether a string is a keyword in Python. 7 | 8 | 9 | This module allows a Python program to determine if a string is a keyword. 10 | 11 | 12 | .. function:: iskeyword(s) 13 | 14 | Return true if *s* is a Python keyword. 15 | 16 | 17 | .. data:: kwlist 18 | 19 | Sequence containing all the keywords defined for the interpreter. If any 20 | keywords are defined to only be active when particular :mod:`__future__` 21 | statements are in effect, these will be included as well. 22 | 23 | 24 | .. seealso:: 25 | 26 | Latest version of the `keyword module Python source code 27 | `_ 28 | -------------------------------------------------------------------------------- /library/language.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _language: 3 | 4 | ************************ 5 | Python Language Services 6 | ************************ 7 | 8 | Python provides a number of modules to assist in working with the Python 9 | language. These modules support tokenizing, parsing, syntax analysis, bytecode 10 | disassembly, and various other facilities. 11 | 12 | These modules include: 13 | 14 | 15 | .. toctree:: 16 | 17 | parser.rst 18 | ast.rst 19 | symtable.rst 20 | symbol.rst 21 | token.rst 22 | keyword.rst 23 | tokenize.rst 24 | tabnanny.rst 25 | pyclbr.rst 26 | py_compile.rst 27 | compileall.rst 28 | dis.rst 29 | pickletools.rst 30 | -------------------------------------------------------------------------------- /library/linecache.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`linecache` --- Random access to text lines 3 | ================================================ 4 | 5 | .. module:: linecache 6 | :synopsis: This module provides random access to individual lines from text files. 7 | .. sectionauthor:: Moshe Zadka 8 | 9 | 10 | The :mod:`linecache` module allows one to get any line from any file, while 11 | attempting to optimize internally, using a cache, the common case where many 12 | lines are read from a single file. This is used by the :mod:`traceback` module 13 | to retrieve source lines for inclusion in the formatted traceback. 14 | 15 | .. seealso:: 16 | 17 | Latest version of the `linecache module Python source code 18 | `_ 19 | 20 | The :mod:`linecache` module defines the following functions: 21 | 22 | 23 | .. function:: getline(filename, lineno[, module_globals]) 24 | 25 | Get line *lineno* from file named *filename*. This function will never raise an 26 | exception --- it will return ``''`` on errors (the terminating newline character 27 | will be included for lines that are found). 28 | 29 | .. index:: triple: module; search; path 30 | 31 | If a file named *filename* is not found, the function will look for it in the 32 | module search path, ``sys.path``, after first checking for a :pep:`302` 33 | ``__loader__`` in *module_globals*, in case the module was imported from a 34 | zipfile or other non-filesystem import source. 35 | 36 | .. versionadded:: 2.5 37 | The *module_globals* parameter was added. 38 | 39 | 40 | .. function:: clearcache() 41 | 42 | Clear the cache. Use this function if you no longer need lines from files 43 | previously read using :func:`getline`. 44 | 45 | 46 | .. function:: checkcache([filename]) 47 | 48 | Check the cache for validity. Use this function if files in the cache may have 49 | changed on disk, and you require the updated version. If *filename* is omitted, 50 | it will check all the entries in the cache. 51 | 52 | Example:: 53 | 54 | >>> import linecache 55 | >>> linecache.getline('/etc/passwd', 4) 56 | 'sys:x:3:3:sys:/dev:/bin/sh\n' 57 | 58 | -------------------------------------------------------------------------------- /library/mac.rst: -------------------------------------------------------------------------------- 1 | .. _mac-specific-services: 2 | 3 | ************************** 4 | Mac OS X specific services 5 | ************************** 6 | 7 | This chapter describes modules that are only available on the Mac OS X platform. 8 | 9 | See the chapters :ref:`mac-scripting` and :ref:`undoc-mac-modules` for more 10 | modules, and the HOWTO :ref:`using-on-mac` for a general introduction to 11 | Mac-specific Python programming. 12 | 13 | .. note:: 14 | 15 | These modules are deprecated and have been removed in Python 3.x. 16 | 17 | 18 | .. toctree:: 19 | 20 | ic.rst 21 | macos.rst 22 | macostools.rst 23 | easydialogs.rst 24 | framework.rst 25 | autogil.rst 26 | carbon.rst 27 | colorpicker.rst 28 | -------------------------------------------------------------------------------- /library/macpath.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`macpath` --- Mac OS 9 path manipulation functions 3 | ======================================================= 4 | 5 | .. module:: macpath 6 | :synopsis: Mac OS 9 path manipulation functions. 7 | 8 | 9 | This module is the Mac OS 9 (and earlier) implementation of the :mod:`os.path` 10 | module. It can be used to manipulate old-style Macintosh pathnames on Mac OS X 11 | (or any other platform). 12 | 13 | The following functions are available in this module: :func:`normcase`, 14 | :func:`normpath`, :func:`isabs`, :func:`join`, :func:`split`, :func:`isdir`, 15 | :func:`isfile`, :func:`walk`, :func:`exists`. For other functions available in 16 | :mod:`os.path` dummy counterparts are available. 17 | 18 | -------------------------------------------------------------------------------- /library/markup.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _markup: 3 | 4 | ********************************** 5 | Structured Markup Processing Tools 6 | ********************************** 7 | 8 | Python supports a variety of modules to work with various forms of structured 9 | data markup. This includes modules to work with the Standard Generalized Markup 10 | Language (SGML) and the Hypertext Markup Language (HTML), and several interfaces 11 | for working with the Extensible Markup Language (XML). 12 | 13 | It is important to note that modules in the :mod:`xml` package require that 14 | there be at least one SAX-compliant XML parser available. Starting with Python 15 | 2.3, the Expat parser is included with Python, so the :mod:`xml.parsers.expat` 16 | module will always be available. You may still want to be aware of the `PyXML 17 | add-on package `_; that package provides an 18 | extended set of XML libraries for Python. 19 | 20 | The documentation for the :mod:`xml.dom` and :mod:`xml.sax` packages are the 21 | definition of the Python bindings for the DOM and SAX interfaces. 22 | 23 | 24 | .. toctree:: 25 | 26 | htmlparser.rst 27 | sgmllib.rst 28 | htmllib.rst 29 | pyexpat.rst 30 | xml.dom.rst 31 | xml.dom.minidom.rst 32 | xml.dom.pulldom.rst 33 | xml.sax.rst 34 | xml.sax.handler.rst 35 | xml.sax.utils.rst 36 | xml.sax.reader.rst 37 | xml.etree.elementtree.rst 38 | -------------------------------------------------------------------------------- /library/miniaeframe.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`MiniAEFrame` --- Open Scripting Architecture server support 3 | ================================================================= 4 | 5 | .. module:: MiniAEFrame 6 | :platform: Mac 7 | :synopsis: Support to act as an Open Scripting Architecture (OSA) server ("Apple Events"). 8 | 9 | 10 | .. index:: 11 | single: Open Scripting Architecture 12 | single: AppleEvents 13 | module: FrameWork 14 | 15 | The module :mod:`MiniAEFrame` provides a framework for an application that can 16 | function as an Open Scripting Architecture (OSA) server, i.e. receive and 17 | process AppleEvents. It can be used in conjunction with :mod:`FrameWork` or 18 | standalone. As an example, it is used in :program:`PythonCGISlave`. 19 | 20 | The :mod:`MiniAEFrame` module defines the following classes: 21 | 22 | 23 | .. class:: AEServer() 24 | 25 | A class that handles AppleEvent dispatch. Your application should subclass this 26 | class together with either :class:`MiniApplication` or 27 | :class:`FrameWork.Application`. Your :meth:`__init__` method should call the 28 | :meth:`__init__` method for both classes. 29 | 30 | 31 | .. class:: MiniApplication() 32 | 33 | A class that is more or less compatible with :class:`FrameWork.Application` but 34 | with less functionality. Its event loop supports the apple menu, command-dot and 35 | AppleEvents; other events are passed on to the Python interpreter and/or Sioux. 36 | Useful if your application wants to use :class:`AEServer` but does not provide 37 | its own windows, etc. 38 | 39 | 40 | .. _aeserver-objects: 41 | 42 | AEServer Objects 43 | ---------------- 44 | 45 | 46 | .. method:: AEServer.installaehandler(classe, type, callback) 47 | 48 | Installs an AppleEvent handler. *classe* and *type* are the four-character OSA 49 | Class and Type designators, ``'****'`` wildcards are allowed. When a matching 50 | AppleEvent is received the parameters are decoded and your callback is invoked. 51 | 52 | 53 | .. method:: AEServer.callback(_object, **kwargs) 54 | 55 | Your callback is called with the OSA Direct Object as first positional 56 | parameter. The other parameters are passed as keyword arguments, with the 57 | 4-character designator as name. Three extra keyword parameters are passed: 58 | ``_class`` and ``_type`` are the Class and Type designators and ``_attributes`` 59 | is a dictionary with the AppleEvent attributes. 60 | 61 | The return value of your method is packed with :func:`aetools.packevent` and 62 | sent as reply. 63 | 64 | Note that there are some serious problems with the current design. AppleEvents 65 | which have non-identifier 4-character designators for arguments are not 66 | implementable, and it is not possible to return an error to the originator. This 67 | will be addressed in a future release. 68 | 69 | -------------------------------------------------------------------------------- /library/misc.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _misc: 3 | 4 | ********************** 5 | Miscellaneous Services 6 | ********************** 7 | 8 | The modules described in this chapter provide miscellaneous services that are 9 | available in all Python versions. Here's an overview: 10 | 11 | 12 | .. toctree:: 13 | 14 | formatter.rst 15 | -------------------------------------------------------------------------------- /library/mm.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _mmedia: 3 | 4 | ******************* 5 | Multimedia Services 6 | ******************* 7 | 8 | The modules described in this chapter implement various algorithms or interfaces 9 | that are mainly useful for multimedia applications. They are available at the 10 | discretion of the installation. Here's an overview: 11 | 12 | 13 | .. toctree:: 14 | 15 | audioop.rst 16 | imageop.rst 17 | aifc.rst 18 | sunau.rst 19 | wave.rst 20 | chunk.rst 21 | colorsys.rst 22 | imghdr.rst 23 | sndhdr.rst 24 | ossaudiodev.rst 25 | -------------------------------------------------------------------------------- /library/modules.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _modules: 3 | 4 | ***************** 5 | Importing Modules 6 | ***************** 7 | 8 | The modules described in this chapter provide new ways to import other Python 9 | modules and hooks for customizing the import process. 10 | 11 | The full list of modules described in this chapter is: 12 | 13 | 14 | .. toctree:: 15 | 16 | imp.rst 17 | importlib.rst 18 | imputil.rst 19 | zipimport.rst 20 | pkgutil.rst 21 | modulefinder.rst 22 | runpy.rst 23 | -------------------------------------------------------------------------------- /library/mutex.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`mutex` --- Mutual exclusion support 3 | ========================================= 4 | 5 | .. module:: mutex 6 | :synopsis: Lock and queue for mutual exclusion. 7 | :deprecated: 8 | 9 | .. deprecated:: 2.6 10 | The :mod:`mutex` module has been removed in Python 3.0. 11 | 12 | .. sectionauthor:: Moshe Zadka 13 | 14 | 15 | The :mod:`mutex` module defines a class that allows mutual-exclusion via 16 | acquiring and releasing locks. It does not require (or imply) 17 | :mod:`threading` or multi-tasking, though it could be useful for those 18 | purposes. 19 | 20 | The :mod:`mutex` module defines the following class: 21 | 22 | 23 | .. class:: mutex() 24 | 25 | Create a new (unlocked) mutex. 26 | 27 | A mutex has two pieces of state --- a "locked" bit and a queue. When the mutex 28 | is not locked, the queue is empty. Otherwise, the queue contains zero or more 29 | ``(function, argument)`` pairs representing functions (or methods) waiting to 30 | acquire the lock. When the mutex is unlocked while the queue is not empty, the 31 | first queue entry is removed and its ``function(argument)`` pair called, 32 | implying it now has the lock. 33 | 34 | Of course, no multi-threading is implied -- hence the funny interface for 35 | :meth:`lock`, where a function is called once the lock is acquired. 36 | 37 | 38 | .. _mutex-objects: 39 | 40 | Mutex Objects 41 | ------------- 42 | 43 | :class:`mutex` objects have following methods: 44 | 45 | 46 | .. method:: mutex.test() 47 | 48 | Check whether the mutex is locked. 49 | 50 | 51 | .. method:: mutex.testandset() 52 | 53 | "Atomic" test-and-set, grab the lock if it is not set, and return ``True``, 54 | otherwise, return ``False``. 55 | 56 | 57 | .. method:: mutex.lock(function, argument) 58 | 59 | Execute ``function(argument)``, unless the mutex is locked. In the case it is 60 | locked, place the function and argument on the queue. See :meth:`unlock` for 61 | explanation of when ``function(argument)`` is executed in that case. 62 | 63 | 64 | .. method:: mutex.unlock() 65 | 66 | Unlock the mutex if queue is empty, otherwise execute the first element in the 67 | queue. 68 | 69 | -------------------------------------------------------------------------------- /library/netdata.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _netdata: 3 | 4 | ********************** 5 | Internet Data Handling 6 | ********************** 7 | 8 | This chapter describes modules which support handling data formats commonly used 9 | on the Internet. 10 | 11 | 12 | .. toctree:: 13 | 14 | email.rst 15 | json.rst 16 | mailcap.rst 17 | mailbox.rst 18 | mhlib.rst 19 | mimetools.rst 20 | mimetypes.rst 21 | mimewriter.rst 22 | mimify.rst 23 | multifile.rst 24 | rfc822.rst 25 | base64.rst 26 | binhex.rst 27 | binascii.rst 28 | quopri.rst 29 | uu.rst 30 | -------------------------------------------------------------------------------- /library/netrc.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`netrc` --- netrc file processing 3 | ====================================== 4 | 5 | .. module:: netrc 6 | :synopsis: Loading of .netrc files. 7 | .. moduleauthor:: Eric S. Raymond 8 | .. sectionauthor:: Eric S. Raymond 9 | 10 | 11 | .. versionadded:: 1.5.2 12 | 13 | The :class:`netrc` class parses and encapsulates the netrc file format used by 14 | the Unix :program:`ftp` program and other FTP clients. 15 | 16 | 17 | .. class:: netrc([file]) 18 | 19 | A :class:`netrc` instance or subclass instance encapsulates data from a netrc 20 | file. The initialization argument, if present, specifies the file to parse. If 21 | no argument is given, the file :file:`.netrc` in the user's home directory will 22 | be read. Parse errors will raise :exc:`NetrcParseError` with diagnostic 23 | information including the file name, line number, and terminating token. 24 | 25 | 26 | .. exception:: NetrcParseError 27 | 28 | Exception raised by the :class:`netrc` class when syntactical errors are 29 | encountered in source text. Instances of this exception provide three 30 | interesting attributes: :attr:`msg` is a textual explanation of the error, 31 | :attr:`filename` is the name of the source file, and :attr:`lineno` gives the 32 | line number on which the error was found. 33 | 34 | 35 | .. _netrc-objects: 36 | 37 | netrc Objects 38 | ------------- 39 | 40 | A :class:`netrc` instance has the following methods: 41 | 42 | 43 | .. method:: netrc.authenticators(host) 44 | 45 | Return a 3-tuple ``(login, account, password)`` of authenticators for *host*. 46 | If the netrc file did not contain an entry for the given host, return the tuple 47 | associated with the 'default' entry. If neither matching host nor default entry 48 | is available, return ``None``. 49 | 50 | 51 | .. method:: netrc.__repr__() 52 | 53 | Dump the class data as a string in the format of a netrc file. (This discards 54 | comments and may reorder the entries.) 55 | 56 | Instances of :class:`netrc` have public instance variables: 57 | 58 | 59 | .. attribute:: netrc.hosts 60 | 61 | Dictionary mapping host names to ``(login, account, password)`` tuples. The 62 | 'default' entry, if any, is represented as a pseudo-host by that name. 63 | 64 | 65 | .. attribute:: netrc.macros 66 | 67 | Dictionary mapping macro names to string lists. 68 | 69 | .. note:: 70 | 71 | Passwords are limited to a subset of the ASCII character set. Versions of 72 | this module prior to 2.3 were extremely limited. Starting with 2.3, all 73 | ASCII punctuation is allowed in passwords. However, note that whitespace and 74 | non-printable characters are not allowed in passwords. This is a limitation 75 | of the way the .netrc file is parsed and may be removed in the future. 76 | 77 | -------------------------------------------------------------------------------- /library/new.rst: -------------------------------------------------------------------------------- 1 | :mod:`new` --- Creation of runtime internal objects 2 | =================================================== 3 | 4 | .. module:: new 5 | :synopsis: Interface to the creation of runtime implementation objects. 6 | :deprecated: 7 | 8 | .. deprecated:: 2.6 9 | The :mod:`new` module has been removed in Python 3.0. Use the :mod:`types` 10 | module's classes instead. 11 | 12 | .. sectionauthor:: Moshe Zadka 13 | 14 | 15 | The :mod:`new` module allows an interface to the interpreter object creation 16 | functions. This is for use primarily in marshal-type functions, when a new 17 | object needs to be created "magically" and not by using the regular creation 18 | functions. This module provides a low-level interface to the interpreter, so 19 | care must be exercised when using this module. It is possible to supply 20 | non-sensical arguments which crash the interpreter when the object is used. 21 | 22 | The :mod:`new` module defines the following functions: 23 | 24 | 25 | .. function:: instance(class[, dict]) 26 | 27 | This function creates an instance of *class* with dictionary *dict* without 28 | calling the :meth:`__init__` constructor. If *dict* is omitted or ``None``, a 29 | new, empty dictionary is created for the new instance. Note that there are no 30 | guarantees that the object will be in a consistent state. 31 | 32 | 33 | .. function:: instancemethod(function, instance, class) 34 | 35 | This function will return a method object, bound to *instance*, or unbound if 36 | *instance* is ``None``. *function* must be callable. 37 | 38 | 39 | .. function:: function(code, globals[, name[, argdefs[, closure]]]) 40 | 41 | Returns a (Python) function with the given code and globals. If *name* is given, 42 | it must be a string or ``None``. If it is a string, the function will have the 43 | given name, otherwise the function name will be taken from ``code.co_name``. If 44 | *argdefs* is given, it must be a tuple and will be used to determine the default 45 | values of parameters. If *closure* is given, it must be ``None`` or a tuple of 46 | cell objects containing objects to bind to the names in ``code.co_freevars``. 47 | 48 | 49 | .. function:: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) 50 | 51 | This function is an interface to the :cfunc:`PyCode_New` C function. 52 | 53 | .. XXX This is still undocumented! 54 | 55 | 56 | .. function:: module(name[, doc]) 57 | 58 | This function returns a new module object with name *name*. *name* must be a 59 | string. The optional *doc* argument can have any type. 60 | 61 | 62 | .. function:: classobj(name, baseclasses, dict) 63 | 64 | This function returns a new class object, with name *name*, derived from 65 | *baseclasses* (which should be a tuple of classes) and with namespace *dict*. 66 | 67 | -------------------------------------------------------------------------------- /library/nis.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`nis` --- Interface to Sun's NIS (Yellow Pages) 3 | ==================================================== 4 | 5 | .. module:: nis 6 | :platform: Unix 7 | :synopsis: Interface to Sun's NIS (Yellow Pages) library. 8 | .. moduleauthor:: Fred Gansevles 9 | .. sectionauthor:: Moshe Zadka 10 | 11 | 12 | The :mod:`nis` module gives a thin wrapper around the NIS library, useful for 13 | central administration of several hosts. 14 | 15 | Because NIS exists only on Unix systems, this module is only available for Unix. 16 | 17 | The :mod:`nis` module defines the following functions: 18 | 19 | 20 | .. function:: match(key, mapname[, domain=default_domain]) 21 | 22 | Return the match for *key* in map *mapname*, or raise an error 23 | (:exc:`nis.error`) if there is none. Both should be strings, *key* is 8-bit 24 | clean. Return value is an arbitrary array of bytes (may contain ``NULL`` and 25 | other joys). 26 | 27 | Note that *mapname* is first checked if it is an alias to another name. 28 | 29 | .. versionchanged:: 2.5 30 | The *domain* argument allows to override the NIS domain used for the lookup. If 31 | unspecified, lookup is in the default NIS domain. 32 | 33 | 34 | .. function:: cat(mapname[, domain=default_domain]) 35 | 36 | Return a dictionary mapping *key* to *value* such that ``match(key, 37 | mapname)==value``. Note that both keys and values of the dictionary are 38 | arbitrary arrays of bytes. 39 | 40 | Note that *mapname* is first checked if it is an alias to another name. 41 | 42 | .. versionchanged:: 2.5 43 | The *domain* argument allows to override the NIS domain used for the lookup. If 44 | unspecified, lookup is in the default NIS domain. 45 | 46 | 47 | .. function:: maps([domain=default_domain]) 48 | 49 | Return a list of all valid maps. 50 | 51 | .. versionchanged:: 2.5 52 | The *domain* argument allows to override the NIS domain used for the lookup. If 53 | unspecified, lookup is in the default NIS domain. 54 | 55 | 56 | .. function:: get_default_domain() 57 | 58 | Return the system default NIS domain. 59 | 60 | .. versionadded:: 2.5 61 | 62 | The :mod:`nis` module defines the following exception: 63 | 64 | 65 | .. exception:: error 66 | 67 | An error raised when a NIS function returns an error code. 68 | 69 | -------------------------------------------------------------------------------- /library/numeric.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _numeric: 3 | 4 | ******************************** 5 | Numeric and Mathematical Modules 6 | ******************************** 7 | 8 | The modules described in this chapter provide numeric and math-related functions 9 | and data types. The :mod:`numbers` module defines an abstract hierarchy of 10 | numeric types. The :mod:`math` and :mod:`cmath` modules contain various 11 | mathematical functions for floating-point and complex numbers. For users more 12 | interested in decimal accuracy than in speed, the :mod:`decimal` module supports 13 | exact representations of decimal numbers. 14 | 15 | The following modules are documented in this chapter: 16 | 17 | 18 | .. toctree:: 19 | 20 | numbers.rst 21 | math.rst 22 | cmath.rst 23 | decimal.rst 24 | fractions.rst 25 | random.rst 26 | itertools.rst 27 | functools.rst 28 | operator.rst 29 | -------------------------------------------------------------------------------- /library/persistence.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _persistence: 3 | 4 | **************** 5 | Data Persistence 6 | **************** 7 | 8 | The modules described in this chapter support storing Python data in a 9 | persistent form on disk. The :mod:`pickle` and :mod:`marshal` modules can turn 10 | many Python data types into a stream of bytes and then recreate the objects from 11 | the bytes. The various DBM-related modules support a family of hash-based file 12 | formats that store a mapping of strings to other strings. The :mod:`bsddb` 13 | module also provides such disk-based string-to-string mappings based on hashing, 14 | and also supports B-Tree and record-based formats. 15 | 16 | The list of modules described in this chapter is: 17 | 18 | 19 | .. toctree:: 20 | 21 | pickle.rst 22 | copy_reg.rst 23 | shelve.rst 24 | marshal.rst 25 | anydbm.rst 26 | whichdb.rst 27 | dbm.rst 28 | gdbm.rst 29 | dbhash.rst 30 | bsddb.rst 31 | dumbdbm.rst 32 | sqlite3.rst 33 | -------------------------------------------------------------------------------- /library/pickletools.rst: -------------------------------------------------------------------------------- 1 | :mod:`pickletools` --- Tools for pickle developers 2 | ================================================== 3 | 4 | .. module:: pickletools 5 | :synopsis: Contains extensive comments about the pickle protocols and pickle-machine 6 | opcodes, as well as some useful functions. 7 | 8 | 9 | .. versionadded:: 2.3 10 | 11 | This module contains various constants relating to the intimate details of the 12 | :mod:`pickle` module, some lengthy comments about the implementation, and a few 13 | useful functions for analyzing pickled data. The contents of this module are 14 | useful for Python core developers who are working on the :mod:`pickle` and 15 | :mod:`cPickle` implementations; ordinary users of the :mod:`pickle` module 16 | probably won't find the :mod:`pickletools` module relevant. 17 | 18 | 19 | .. function:: dis(pickle[, out=None, memo=None, indentlevel=4]) 20 | 21 | Outputs a symbolic disassembly of the pickle to the file-like object *out*, 22 | defaulting to ``sys.stdout``. *pickle* can be a string or a file-like object. 23 | *memo* can be a Python dictionary that will be used as the pickle's memo; it can 24 | be used to perform disassemblies across multiple pickles created by the same 25 | pickler. Successive levels, indicated by ``MARK`` opcodes in the stream, are 26 | indented by *indentlevel* spaces. 27 | 28 | 29 | .. function:: genops(pickle) 30 | 31 | Provides an :term:`iterator` over all of the opcodes in a pickle, returning a 32 | sequence of ``(opcode, arg, pos)`` triples. *opcode* is an instance of an 33 | :class:`OpcodeInfo` class; *arg* is the decoded value, as a Python object, of 34 | the opcode's argument; *pos* is the position at which this opcode is located. 35 | *pickle* can be a string or a file-like object. 36 | 37 | .. function:: optimize(picklestring) 38 | 39 | Returns a new equivalent pickle string after eliminating unused ``PUT`` 40 | opcodes. The optimized pickle is shorter, takes less transmission time, 41 | requires less storage space, and unpickles more efficiently. 42 | 43 | .. versionadded:: 2.6 44 | -------------------------------------------------------------------------------- /library/pipes.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`pipes` --- Interface to shell pipelines 3 | ============================================= 4 | 5 | .. module:: pipes 6 | :platform: Unix 7 | :synopsis: A Python interface to Unix shell pipelines. 8 | .. sectionauthor:: Moshe Zadka 9 | 10 | 11 | The :mod:`pipes` module defines a class to abstract the concept of a *pipeline* 12 | --- a sequence of converters from one file to another. 13 | 14 | Because the module uses :program:`/bin/sh` command lines, a POSIX or compatible 15 | shell for :func:`os.system` and :func:`os.popen` is required. 16 | 17 | The :mod:`pipes` module defines the following class: 18 | 19 | 20 | .. class:: Template() 21 | 22 | An abstraction of a pipeline. 23 | 24 | Example:: 25 | 26 | >>> import pipes 27 | >>> t=pipes.Template() 28 | >>> t.append('tr a-z A-Z', '--') 29 | >>> f=t.open('/tmp/1', 'w') 30 | >>> f.write('hello world') 31 | >>> f.close() 32 | >>> open('/tmp/1').read() 33 | 'HELLO WORLD' 34 | 35 | 36 | .. _template-objects: 37 | 38 | Template Objects 39 | ---------------- 40 | 41 | Template objects following methods: 42 | 43 | 44 | .. method:: Template.reset() 45 | 46 | Restore a pipeline template to its initial state. 47 | 48 | 49 | .. method:: Template.clone() 50 | 51 | Return a new, equivalent, pipeline template. 52 | 53 | 54 | .. method:: Template.debug(flag) 55 | 56 | If *flag* is true, turn debugging on. Otherwise, turn debugging off. When 57 | debugging is on, commands to be executed are printed, and the shell is given 58 | ``set -x`` command to be more verbose. 59 | 60 | 61 | .. method:: Template.append(cmd, kind) 62 | 63 | Append a new action at the end. The *cmd* variable must be a valid bourne shell 64 | command. The *kind* variable consists of two letters. 65 | 66 | The first letter can be either of ``'-'`` (which means the command reads its 67 | standard input), ``'f'`` (which means the commands reads a given file on the 68 | command line) or ``'.'`` (which means the commands reads no input, and hence 69 | must be first.) 70 | 71 | Similarly, the second letter can be either of ``'-'`` (which means the command 72 | writes to standard output), ``'f'`` (which means the command writes a file on 73 | the command line) or ``'.'`` (which means the command does not write anything, 74 | and hence must be last.) 75 | 76 | 77 | .. method:: Template.prepend(cmd, kind) 78 | 79 | Add a new action at the beginning. See :meth:`append` for explanations of the 80 | arguments. 81 | 82 | 83 | .. method:: Template.open(file, mode) 84 | 85 | Return a file-like object, open to *file*, but read from or written to by the 86 | pipeline. Note that only one of ``'r'``, ``'w'`` may be given. 87 | 88 | 89 | .. method:: Template.copy(infile, outfile) 90 | 91 | Copy *infile* to *outfile* through the pipe. 92 | 93 | -------------------------------------------------------------------------------- /library/pty.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`pty` --- Pseudo-terminal utilities 3 | ======================================== 4 | 5 | .. module:: pty 6 | :platform: Linux 7 | :synopsis: Pseudo-Terminal Handling for Linux. 8 | .. moduleauthor:: Steen Lumholt 9 | .. sectionauthor:: Moshe Zadka 10 | 11 | 12 | The :mod:`pty` module defines operations for handling the pseudo-terminal 13 | concept: starting another process and being able to write to and read from its 14 | controlling terminal programmatically. 15 | 16 | Because pseudo-terminal handling is highly platform dependent, there is code to 17 | do it only for Linux. (The Linux code is supposed to work on other platforms, 18 | but hasn't been tested yet.) 19 | 20 | The :mod:`pty` module defines the following functions: 21 | 22 | 23 | .. function:: fork() 24 | 25 | Fork. Connect the child's controlling terminal to a pseudo-terminal. Return 26 | value is ``(pid, fd)``. Note that the child gets *pid* 0, and the *fd* is 27 | *invalid*. The parent's return value is the *pid* of the child, and *fd* is a 28 | file descriptor connected to the child's controlling terminal (and also to the 29 | child's standard input and output). 30 | 31 | 32 | .. function:: openpty() 33 | 34 | Open a new pseudo-terminal pair, using :func:`os.openpty` if possible, or 35 | emulation code for generic Unix systems. Return a pair of file descriptors 36 | ``(master, slave)``, for the master and the slave end, respectively. 37 | 38 | 39 | .. function:: spawn(argv[, master_read[, stdin_read]]) 40 | 41 | Spawn a process, and connect its controlling terminal with the current 42 | process's standard io. This is often used to baffle programs which insist on 43 | reading from the controlling terminal. 44 | 45 | The functions *master_read* and *stdin_read* should be functions which read from 46 | a file descriptor. The defaults try to read 1024 bytes each time they are 47 | called. 48 | 49 | -------------------------------------------------------------------------------- /library/pwd.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`pwd` --- The password database 3 | ==================================== 4 | 5 | .. module:: pwd 6 | :platform: Unix 7 | :synopsis: The password database (getpwnam() and friends). 8 | 9 | 10 | This module provides access to the Unix user account and password database. It 11 | is available on all Unix versions. 12 | 13 | Password database entries are reported as a tuple-like object, whose attributes 14 | correspond to the members of the ``passwd`` structure (Attribute field below, 15 | see ````): 16 | 17 | +-------+---------------+-----------------------------+ 18 | | Index | Attribute | Meaning | 19 | +=======+===============+=============================+ 20 | | 0 | ``pw_name`` | Login name | 21 | +-------+---------------+-----------------------------+ 22 | | 1 | ``pw_passwd`` | Optional encrypted password | 23 | +-------+---------------+-----------------------------+ 24 | | 2 | ``pw_uid`` | Numerical user ID | 25 | +-------+---------------+-----------------------------+ 26 | | 3 | ``pw_gid`` | Numerical group ID | 27 | +-------+---------------+-----------------------------+ 28 | | 4 | ``pw_gecos`` | User name or comment field | 29 | +-------+---------------+-----------------------------+ 30 | | 5 | ``pw_dir`` | User home directory | 31 | +-------+---------------+-----------------------------+ 32 | | 6 | ``pw_shell`` | User command interpreter | 33 | +-------+---------------+-----------------------------+ 34 | 35 | The uid and gid items are integers, all others are strings. :exc:`KeyError` is 36 | raised if the entry asked for cannot be found. 37 | 38 | .. note:: 39 | 40 | .. index:: module: crypt 41 | 42 | In traditional Unix the field ``pw_passwd`` usually contains a password 43 | encrypted with a DES derived algorithm (see module :mod:`crypt`). However most 44 | modern unices use a so-called *shadow password* system. On those unices the 45 | *pw_passwd* field only contains an asterisk (``'*'``) or the letter ``'x'`` 46 | where the encrypted password is stored in a file :file:`/etc/shadow` which is 47 | not world readable. Whether the *pw_passwd* field contains anything useful is 48 | system-dependent. If available, the :mod:`spwd` module should be used where 49 | access to the encrypted password is required. 50 | 51 | It defines the following items: 52 | 53 | 54 | .. function:: getpwuid(uid) 55 | 56 | Return the password database entry for the given numeric user ID. 57 | 58 | 59 | .. function:: getpwnam(name) 60 | 61 | Return the password database entry for the given user name. 62 | 63 | 64 | .. function:: getpwall() 65 | 66 | Return a list of all available password database entries, in arbitrary order. 67 | 68 | 69 | .. seealso:: 70 | 71 | Module :mod:`grp` 72 | An interface to the group database, similar to this. 73 | 74 | Module :mod:`spwd` 75 | An interface to the shadow password database, similar to this. 76 | 77 | -------------------------------------------------------------------------------- /library/py_compile.rst: -------------------------------------------------------------------------------- 1 | :mod:`py_compile` --- Compile Python source files 2 | ================================================= 3 | 4 | .. module:: py_compile 5 | :synopsis: Generate byte-code files from Python source files. 6 | .. sectionauthor:: Fred L. Drake, Jr. 7 | .. documentation based on module docstrings 8 | 9 | .. index:: pair: file; byte-code 10 | 11 | The :mod:`py_compile` module provides a function to generate a byte-code file 12 | from a source file, and another function used when the module source file is 13 | invoked as a script. 14 | 15 | Though not often needed, this function can be useful when installing modules for 16 | shared use, especially if some of the users may not have permission to write the 17 | byte-code cache files in the directory containing the source code. 18 | 19 | 20 | .. exception:: PyCompileError 21 | 22 | Exception raised when an error occurs while attempting to compile the file. 23 | 24 | 25 | .. function:: compile(file[, cfile[, dfile[, doraise]]]) 26 | 27 | Compile a source file to byte-code and write out the byte-code cache file. The 28 | source code is loaded from the file name *file*. The byte-code is written to 29 | *cfile*, which defaults to *file* ``+`` ``'c'`` (``'o'`` if optimization is 30 | enabled in the current interpreter). If *dfile* is specified, it is used as the 31 | name of the source file in error messages instead of *file*. If *doraise* is 32 | true, a :exc:`PyCompileError` is raised when an error is encountered while 33 | compiling *file*. If *doraise* is false (the default), an error string is 34 | written to ``sys.stderr``, but no exception is raised. 35 | 36 | 37 | .. function:: main([args]) 38 | 39 | Compile several source files. The files named in *args* (or on the command 40 | line, if *args* is not specified) are compiled and the resulting bytecode is 41 | cached in the normal manner. This function does not search a directory 42 | structure to locate source files; it only compiles files named explicitly. 43 | If ``'-'`` is the only parameter in args, the list of files is taken from 44 | standard input. 45 | 46 | .. versionchanged:: 2.7 47 | Added support for ``'-'``. 48 | 49 | When this module is run as a script, the :func:`main` is used to compile all the 50 | files named on the command line. The exit status is nonzero if one of the files 51 | could not be compiled. 52 | 53 | .. versionchanged:: 2.6 54 | Added the nonzero exit status when module is run as a script. 55 | 56 | 57 | .. seealso:: 58 | 59 | Module :mod:`compileall` 60 | Utilities to compile all Python source files in a directory tree. 61 | 62 | -------------------------------------------------------------------------------- /library/python.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _python: 3 | 4 | *********************** 5 | Python Runtime Services 6 | *********************** 7 | 8 | The modules described in this chapter provide a wide range of services related 9 | to the Python interpreter and its interaction with its environment. Here's an 10 | overview: 11 | 12 | 13 | .. toctree:: 14 | 15 | sys.rst 16 | sysconfig.rst 17 | __builtin__.rst 18 | future_builtins.rst 19 | __main__.rst 20 | warnings.rst 21 | contextlib.rst 22 | abc.rst 23 | atexit.rst 24 | traceback.rst 25 | __future__.rst 26 | gc.rst 27 | inspect.rst 28 | site.rst 29 | user.rst 30 | fpectl.rst 31 | distutils.rst 32 | -------------------------------------------------------------------------------- /library/rlcompleter.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`rlcompleter` --- Completion function for GNU readline 3 | =========================================================== 4 | 5 | .. module:: rlcompleter 6 | :synopsis: Python identifier completion, suitable for the GNU readline library. 7 | .. sectionauthor:: Moshe Zadka 8 | 9 | 10 | The :mod:`rlcompleter` module defines a completion function suitable for the 11 | :mod:`readline` module by completing valid Python identifiers and keywords. 12 | 13 | When this module is imported on a Unix platform with the :mod:`readline` module 14 | available, an instance of the :class:`Completer` class is automatically created 15 | and its :meth:`complete` method is set as the :mod:`readline` completer. 16 | 17 | Example:: 18 | 19 | >>> import rlcompleter 20 | >>> import readline 21 | >>> readline.parse_and_bind("tab: complete") 22 | >>> readline. 23 | readline.__doc__ readline.get_line_buffer( readline.read_init_file( 24 | readline.__file__ readline.insert_text( readline.set_completer( 25 | readline.__name__ readline.parse_and_bind( 26 | >>> readline. 27 | 28 | The :mod:`rlcompleter` module is designed for use with Python's interactive 29 | mode. A user can add the following lines to his or her initialization file 30 | (identified by the :envvar:`PYTHONSTARTUP` environment variable) to get 31 | automatic :kbd:`Tab` completion:: 32 | 33 | try: 34 | import readline 35 | except ImportError: 36 | print "Module readline not available." 37 | else: 38 | import rlcompleter 39 | readline.parse_and_bind("tab: complete") 40 | 41 | On platforms without :mod:`readline`, the :class:`Completer` class defined by 42 | this module can still be used for custom purposes. 43 | 44 | 45 | .. _completer-objects: 46 | 47 | Completer Objects 48 | ----------------- 49 | 50 | Completer objects have the following method: 51 | 52 | 53 | .. method:: Completer.complete(text, state) 54 | 55 | Return the *state*\ th completion for *text*. 56 | 57 | If called for *text* that doesn't include a period character (``'.'``), it will 58 | complete from names currently defined in :mod:`__main__`, :mod:`__builtin__` and 59 | keywords (as defined by the :mod:`keyword` module). 60 | 61 | If called for a dotted name, it will try to evaluate anything without obvious 62 | side-effects (functions will not be evaluated, but it can generate calls to 63 | :meth:`__getattr__`) up to the last part, and find matches for the rest via the 64 | :func:`dir` function. Any exception raised during the evaluation of the 65 | expression is caught, silenced and :const:`None` is returned. 66 | 67 | -------------------------------------------------------------------------------- /library/robotparser.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`robotparser` --- Parser for robots.txt 3 | ============================================= 4 | 5 | .. module:: robotparser 6 | :synopsis: Loads a robots.txt file and answers questions about 7 | fetchability of other URLs. 8 | .. sectionauthor:: Skip Montanaro 9 | 10 | 11 | .. index:: 12 | single: WWW 13 | single: World Wide Web 14 | single: URL 15 | single: robots.txt 16 | 17 | .. note:: 18 | The :mod:`robotparser` module has been renamed :mod:`urllib.robotparser` in 19 | Python 3.0. 20 | The :term:`2to3` tool will automatically adapt imports when converting 21 | your sources to 3.0. 22 | 23 | This module provides a single class, :class:`RobotFileParser`, which answers 24 | questions about whether or not a particular user agent can fetch a URL on the 25 | Web site that published the :file:`robots.txt` file. For more details on the 26 | structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html. 27 | 28 | 29 | .. class:: RobotFileParser() 30 | 31 | This class provides a set of methods to read, parse and answer questions 32 | about a single :file:`robots.txt` file. 33 | 34 | 35 | .. method:: set_url(url) 36 | 37 | Sets the URL referring to a :file:`robots.txt` file. 38 | 39 | 40 | .. method:: read() 41 | 42 | Reads the :file:`robots.txt` URL and feeds it to the parser. 43 | 44 | 45 | .. method:: parse(lines) 46 | 47 | Parses the lines argument. 48 | 49 | 50 | .. method:: can_fetch(useragent, url) 51 | 52 | Returns ``True`` if the *useragent* is allowed to fetch the *url* 53 | according to the rules contained in the parsed :file:`robots.txt` 54 | file. 55 | 56 | 57 | .. method:: mtime() 58 | 59 | Returns the time the ``robots.txt`` file was last fetched. This is 60 | useful for long-running web spiders that need to check for new 61 | ``robots.txt`` files periodically. 62 | 63 | 64 | .. method:: modified() 65 | 66 | Sets the time the ``robots.txt`` file was last fetched to the current 67 | time. 68 | 69 | The following example demonstrates basic use of the RobotFileParser class. :: 70 | 71 | >>> import robotparser 72 | >>> rp = robotparser.RobotFileParser() 73 | >>> rp.set_url("http://www.musi-cal.com/robots.txt") 74 | >>> rp.read() 75 | >>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco") 76 | False 77 | >>> rp.can_fetch("*", "http://www.musi-cal.com/") 78 | True 79 | 80 | -------------------------------------------------------------------------------- /library/scrolledtext.rst: -------------------------------------------------------------------------------- 1 | :mod:`ScrolledText` --- Scrolled Text Widget 2 | ============================================ 3 | 4 | .. module:: ScrolledText 5 | :platform: Tk 6 | :synopsis: Text widget with a vertical scroll bar. 7 | .. sectionauthor:: Fred L. Drake, Jr. 8 | 9 | 10 | The :mod:`ScrolledText` module provides a class of the same name which 11 | implements a basic text widget which has a vertical scroll bar configured to do 12 | the "right thing." Using the :class:`ScrolledText` class is a lot easier than 13 | setting up a text widget and scroll bar directly. The constructor is the same 14 | as that of the :class:`Tkinter.Text` class. 15 | 16 | .. note:: 17 | 18 | :mod:`ScrolledText` has been renamed to :mod:`tkinter.scrolledtext` in Python 19 | 3.0. The :term:`2to3` tool will automatically adapt imports when converting 20 | your sources to 3.0. 21 | 22 | The text widget and scrollbar are packed together in a :class:`Frame`, and the 23 | methods of the :class:`Grid` and :class:`Pack` geometry managers are acquired 24 | from the :class:`Frame` object. This allows the :class:`ScrolledText` widget to 25 | be used directly to achieve most normal geometry management behavior. 26 | 27 | Should more specific control be necessary, the following attributes are 28 | available: 29 | 30 | 31 | .. attribute:: ScrolledText.frame 32 | 33 | The frame which surrounds the text and scroll bar widgets. 34 | 35 | 36 | .. attribute:: ScrolledText.vbar 37 | 38 | The scroll bar widget. 39 | -------------------------------------------------------------------------------- /library/sgi.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _sgi: 3 | 4 | ************************** 5 | SGI IRIX Specific Services 6 | ************************** 7 | 8 | The modules described in this chapter provide interfaces to features that are 9 | unique to SGI's IRIX operating system (versions 4 and 5). 10 | 11 | 12 | .. toctree:: 13 | 14 | al.rst 15 | cd.rst 16 | fl.rst 17 | fm.rst 18 | gl.rst 19 | imgfile.rst 20 | jpeg.rst 21 | -------------------------------------------------------------------------------- /library/smtpd.rst: -------------------------------------------------------------------------------- 1 | :mod:`smtpd` --- SMTP Server 2 | ============================ 3 | 4 | .. module:: smtpd 5 | :synopsis: A SMTP server implementation in Python. 6 | 7 | .. moduleauthor:: Barry Warsaw 8 | .. sectionauthor:: Moshe Zadka 9 | 10 | 11 | 12 | 13 | This module offers several classes to implement SMTP servers. One is a generic 14 | do-nothing implementation, which can be overridden, while the other two offer 15 | specific mail-sending strategies. 16 | 17 | 18 | SMTPServer Objects 19 | ------------------ 20 | 21 | 22 | .. class:: SMTPServer(localaddr, remoteaddr) 23 | 24 | Create a new :class:`SMTPServer` object, which binds to local address 25 | *localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. It 26 | inherits from :class:`asyncore.dispatcher`, and so will insert itself into 27 | :mod:`asyncore`'s event loop on instantiation. 28 | 29 | 30 | .. method:: process_message(peer, mailfrom, rcpttos, data) 31 | 32 | Raise :exc:`NotImplementedError` exception. Override this in subclasses to 33 | do something useful with this message. Whatever was passed in the 34 | constructor as *remoteaddr* will be available as the :attr:`_remoteaddr` 35 | attribute. *peer* is the remote host's address, *mailfrom* is the envelope 36 | originator, *rcpttos* are the envelope recipients and *data* is a string 37 | containing the contents of the e-mail (which should be in :rfc:`2822` 38 | format). 39 | 40 | 41 | DebuggingServer Objects 42 | ----------------------- 43 | 44 | 45 | .. class:: DebuggingServer(localaddr, remoteaddr) 46 | 47 | Create a new debugging server. Arguments are as per :class:`SMTPServer`. 48 | Messages will be discarded, and printed on stdout. 49 | 50 | 51 | PureProxy Objects 52 | ----------------- 53 | 54 | 55 | .. class:: PureProxy(localaddr, remoteaddr) 56 | 57 | Create a new pure proxy server. Arguments are as per :class:`SMTPServer`. 58 | Everything will be relayed to *remoteaddr*. Note that running this has a good 59 | chance to make you into an open relay, so please be careful. 60 | 61 | 62 | MailmanProxy Objects 63 | -------------------- 64 | 65 | 66 | .. class:: MailmanProxy(localaddr, remoteaddr) 67 | 68 | Create a new pure proxy server. Arguments are as per :class:`SMTPServer`. 69 | Everything will be relayed to *remoteaddr*, unless local mailman configurations 70 | knows about an address, in which case it will be handled via mailman. Note that 71 | running this has a good chance to make you into an open relay, so please be 72 | careful. 73 | 74 | -------------------------------------------------------------------------------- /library/sndhdr.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`sndhdr` --- Determine type of sound file 3 | ============================================== 4 | 5 | .. module:: sndhdr 6 | :synopsis: Determine type of a sound file. 7 | .. sectionauthor:: Fred L. Drake, Jr. 8 | .. Based on comments in the module source file. 9 | 10 | .. index:: 11 | single: A-LAW 12 | single: u-LAW 13 | 14 | The :mod:`sndhdr` provides utility functions which attempt to determine the type 15 | of sound data which is in a file. When these functions are able to determine 16 | what type of sound data is stored in a file, they return a tuple ``(type, 17 | sampling_rate, channels, frames, bits_per_sample)``. The value for *type* 18 | indicates the data type and will be one of the strings ``'aifc'``, ``'aiff'``, 19 | ``'au'``, ``'hcom'``, ``'sndr'``, ``'sndt'``, ``'voc'``, ``'wav'``, ``'8svx'``, 20 | ``'sb'``, ``'ub'``, or ``'ul'``. The *sampling_rate* will be either the actual 21 | value or ``0`` if unknown or difficult to decode. Similarly, *channels* will be 22 | either the number of channels or ``0`` if it cannot be determined or if the 23 | value is difficult to decode. The value for *frames* will be either the number 24 | of frames or ``-1``. The last item in the tuple, *bits_per_sample*, will either 25 | be the sample size in bits or ``'A'`` for A-LAW or ``'U'`` for u-LAW. 26 | 27 | 28 | .. function:: what(filename) 29 | 30 | Determines the type of sound data stored in the file *filename* using 31 | :func:`whathdr`. If it succeeds, returns a tuple as described above, otherwise 32 | ``None`` is returned. 33 | 34 | 35 | .. function:: whathdr(filename) 36 | 37 | Determines the type of sound data stored in a file based on the file header. 38 | The name of the file is given by *filename*. This function returns a tuple as 39 | described above on success, or ``None``. 40 | 41 | -------------------------------------------------------------------------------- /library/someos.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _someos: 3 | 4 | ********************************** 5 | Optional Operating System Services 6 | ********************************** 7 | 8 | The modules described in this chapter provide interfaces to operating system 9 | features that are available on selected operating systems only. The interfaces 10 | are generally modeled after the Unix or C interfaces but they are available on 11 | some other systems as well (e.g. Windows or NT). Here's an overview: 12 | 13 | 14 | .. toctree:: 15 | 16 | select.rst 17 | threading.rst 18 | thread.rst 19 | dummy_threading.rst 20 | dummy_thread.rst 21 | multiprocessing.rst 22 | mmap.rst 23 | readline.rst 24 | rlcompleter.rst 25 | -------------------------------------------------------------------------------- /library/statvfs.rst: -------------------------------------------------------------------------------- 1 | :mod:`statvfs` --- Constants used with :func:`os.statvfs` 2 | ========================================================= 3 | 4 | .. module:: statvfs 5 | :synopsis: Constants for interpreting the result of os.statvfs(). 6 | :deprecated: 7 | 8 | .. deprecated:: 2.6 9 | The :mod:`statvfs` module has been deprecated for removal in Python 3.0. 10 | 11 | 12 | .. sectionauthor:: Moshe Zadka 13 | 14 | 15 | The :mod:`statvfs` module defines constants so interpreting the result if 16 | :func:`os.statvfs`, which returns a tuple, can be made without remembering 17 | "magic numbers." Each of the constants defined in this module is the *index* of 18 | the entry in the tuple returned by :func:`os.statvfs` that contains the 19 | specified information. 20 | 21 | 22 | .. data:: F_BSIZE 23 | 24 | Preferred file system block size. 25 | 26 | 27 | .. data:: F_FRSIZE 28 | 29 | Fundamental file system block size. 30 | 31 | 32 | .. data:: F_BLOCKS 33 | 34 | Total number of blocks in the filesystem. 35 | 36 | 37 | .. data:: F_BFREE 38 | 39 | Total number of free blocks. 40 | 41 | 42 | .. data:: F_BAVAIL 43 | 44 | Free blocks available to non-super user. 45 | 46 | 47 | .. data:: F_FILES 48 | 49 | Total number of file nodes. 50 | 51 | 52 | .. data:: F_FFREE 53 | 54 | Total number of free file nodes. 55 | 56 | 57 | .. data:: F_FAVAIL 58 | 59 | Free nodes available to non-super user. 60 | 61 | 62 | .. data:: F_FLAG 63 | 64 | Flags. System dependent: see :cfunc:`statvfs` man page. 65 | 66 | 67 | .. data:: F_NAMEMAX 68 | 69 | Maximum file name length. 70 | 71 | -------------------------------------------------------------------------------- /library/strings.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _stringservices: 3 | 4 | *************** 5 | String Services 6 | *************** 7 | 8 | The modules described in this chapter provide a wide range of string 9 | manipulation operations. 10 | 11 | In addition, Python's built-in string classes support the sequence type 12 | methods described in the :ref:`typesseq` section, and also the 13 | string-specific methods described in the :ref:`string-methods` section. 14 | To output formatted strings use template strings or the ``%`` operator 15 | described in the :ref:`string-formatting` section. Also, see the 16 | :mod:`re` module for string functions based on regular expressions. 17 | 18 | 19 | .. toctree:: 20 | 21 | string.rst 22 | re.rst 23 | struct.rst 24 | difflib.rst 25 | stringio.rst 26 | textwrap.rst 27 | codecs.rst 28 | unicodedata.rst 29 | stringprep.rst 30 | fpformat.rst 31 | 32 | -------------------------------------------------------------------------------- /library/sun.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _sunos: 3 | 4 | *********************** 5 | SunOS Specific Services 6 | *********************** 7 | 8 | The modules described in this chapter provide interfaces to features that are 9 | unique to SunOS 5 (also known as Solaris version 2). 10 | 11 | 12 | .. toctree:: 13 | 14 | sunaudio.rst 15 | -------------------------------------------------------------------------------- /library/symbol.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`symbol` --- Constants used with Python parse trees 3 | ======================================================== 4 | 5 | .. module:: symbol 6 | :synopsis: Constants representing internal nodes of the parse tree. 7 | .. sectionauthor:: Fred L. Drake, Jr. 8 | 9 | 10 | This module provides constants which represent the numeric values of internal 11 | nodes of the parse tree. Unlike most Python constants, these use lower-case 12 | names. Refer to the file :file:`Grammar/Grammar` in the Python distribution for 13 | the definitions of the names in the context of the language grammar. The 14 | specific numeric values which the names map to may change between Python 15 | versions. 16 | 17 | This module also provides one additional data object: 18 | 19 | 20 | .. data:: sym_name 21 | 22 | Dictionary mapping the numeric values of the constants defined in this module 23 | back to name strings, allowing more human-readable representation of parse trees 24 | to be generated. 25 | 26 | 27 | .. seealso:: 28 | 29 | Module :mod:`parser` 30 | The second example for the :mod:`parser` module shows how to use the 31 | :mod:`symbol` module. 32 | 33 | -------------------------------------------------------------------------------- /library/tabnanny.rst: -------------------------------------------------------------------------------- 1 | :mod:`tabnanny` --- Detection of ambiguous indentation 2 | ====================================================== 3 | 4 | .. module:: tabnanny 5 | :synopsis: Tool for detecting white space related problems in Python source files in a 6 | directory tree. 7 | .. moduleauthor:: Tim Peters 8 | .. sectionauthor:: Peter Funk 9 | 10 | .. rudimentary documentation based on module comments 11 | 12 | For the time being this module is intended to be called as a script. However it 13 | is possible to import it into an IDE and use the function :func:`check` 14 | described below. 15 | 16 | .. note:: 17 | 18 | The API provided by this module is likely to change in future releases; such 19 | changes may not be backward compatible. 20 | 21 | 22 | .. function:: check(file_or_dir) 23 | 24 | If *file_or_dir* is a directory and not a symbolic link, then recursively 25 | descend the directory tree named by *file_or_dir*, checking all :file:`.py` 26 | files along the way. If *file_or_dir* is an ordinary Python source file, it is 27 | checked for whitespace related problems. The diagnostic messages are written to 28 | standard output using the print statement. 29 | 30 | 31 | .. data:: verbose 32 | 33 | Flag indicating whether to print verbose messages. This is incremented by the 34 | ``-v`` option if called as a script. 35 | 36 | 37 | .. data:: filename_only 38 | 39 | Flag indicating whether to print only the filenames of files containing 40 | whitespace related problems. This is set to true by the ``-q`` option if called 41 | as a script. 42 | 43 | 44 | .. exception:: NannyNag 45 | 46 | Raised by :func:`tokeneater` if detecting an ambiguous indent. Captured and 47 | handled in :func:`check`. 48 | 49 | 50 | .. function:: tokeneater(type, token, start, end, line) 51 | 52 | This function is used by :func:`check` as a callback parameter to the function 53 | :func:`tokenize.tokenize`. 54 | 55 | .. XXX document errprint, format_witnesses, Whitespace, check_equal, indents, 56 | reset_globals 57 | 58 | 59 | .. seealso:: 60 | 61 | Module :mod:`tokenize` 62 | Lexical scanner for Python source code. 63 | -------------------------------------------------------------------------------- /library/tk.rst: -------------------------------------------------------------------------------- 1 | .. _tkinter: 2 | 3 | ********************************* 4 | Graphical User Interfaces with Tk 5 | ********************************* 6 | 7 | .. index:: 8 | single: GUI 9 | single: Graphical User Interface 10 | single: Tkinter 11 | single: Tk 12 | 13 | Tk/Tcl has long been an integral part of Python. It provides a robust and 14 | platform independent windowing toolkit, that is available to Python programmers 15 | using the :mod:`Tkinter` module, and its extensions, the :mod:`Tix` and 16 | the :mod:`ttk` modules. 17 | 18 | The :mod:`Tkinter` module is a thin object-oriented layer on top of Tcl/Tk. To 19 | use :mod:`Tkinter`, you don't need to write Tcl code, but you will need to 20 | consult the Tk documentation, and occasionally the Tcl documentation. 21 | :mod:`Tkinter` is a set of wrappers that implement the Tk widgets as Python 22 | classes. In addition, the internal module :mod:`_tkinter` provides a threadsafe 23 | mechanism which allows Python and Tcl to interact. 24 | 25 | :mod:`Tkinter`'s chief virtues are that it is fast, and that it usually comes 26 | bundled with Python. Although its standard documentation is weak, good 27 | material is available, which includes: references, tutorials, a book and 28 | others. :mod:`Tkinter` is also famous for having an outdated look and feel, 29 | which has been vastly improved in Tk 8.5. Nevertheless, there are many other 30 | GUI libraries that you could be interested in. For more information about 31 | alternatives, see the :ref:`other-gui-packages` section. 32 | 33 | .. toctree:: 34 | 35 | tkinter.rst 36 | ttk.rst 37 | tix.rst 38 | scrolledtext.rst 39 | turtle.rst 40 | idle.rst 41 | othergui.rst 42 | 43 | .. Other sections I have in mind are 44 | Tkinter internals 45 | Freezing Tkinter applications 46 | 47 | 48 | -------------------------------------------------------------------------------- /library/token.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`token` --- Constants used with Python parse trees 3 | ======================================================= 4 | 5 | .. module:: token 6 | :synopsis: Constants representing terminal nodes of the parse tree. 7 | .. sectionauthor:: Fred L. Drake, Jr. 8 | 9 | 10 | This module provides constants which represent the numeric values of leaf nodes 11 | of the parse tree (terminal tokens). Refer to the file :file:`Grammar/Grammar` 12 | in the Python distribution for the definitions of the names in the context of 13 | the language grammar. The specific numeric values which the names map to may 14 | change between Python versions. 15 | 16 | The module also provides a mapping from numeric codes to names and some 17 | functions. The functions mirror definitions in the Python C header files. 18 | 19 | 20 | .. data:: tok_name 21 | 22 | Dictionary mapping the numeric values of the constants defined in this module 23 | back to name strings, allowing more human-readable representation of parse trees 24 | to be generated. 25 | 26 | 27 | .. function:: ISTERMINAL(x) 28 | 29 | Return true for terminal token values. 30 | 31 | 32 | .. function:: ISNONTERMINAL(x) 33 | 34 | Return true for non-terminal token values. 35 | 36 | 37 | .. function:: ISEOF(x) 38 | 39 | Return true if *x* is the marker indicating the end of input. 40 | 41 | 42 | The token constants are: 43 | 44 | .. data:: ENDMARKER 45 | NAME 46 | NUMBER 47 | STRING 48 | NEWLINE 49 | INDENT 50 | DEDENT 51 | LPAR 52 | RPAR 53 | LSQB 54 | RSQB 55 | COLON 56 | COMMA 57 | SEMI 58 | PLUS 59 | MINUS 60 | STAR 61 | SLASH 62 | VBAR 63 | AMPER 64 | LESS 65 | GREATER 66 | EQUAL 67 | DOT 68 | PERCENT 69 | BACKQUOTE 70 | LBRACE 71 | RBRACE 72 | EQEQUAL 73 | NOTEQUAL 74 | LESSEQUAL 75 | GREATEREQUAL 76 | TILDE 77 | CIRCUMFLEX 78 | LEFTSHIFT 79 | RIGHTSHIFT 80 | DOUBLESTAR 81 | PLUSEQUAL 82 | MINEQUAL 83 | STAREQUAL 84 | SLASHEQUAL 85 | PERCENTEQUAL 86 | AMPEREQUAL 87 | VBAREQUAL 88 | CIRCUMFLEXEQUAL 89 | LEFTSHIFTEQUAL 90 | RIGHTSHIFTEQUAL 91 | DOUBLESTAREQUAL 92 | DOUBLESLASH 93 | DOUBLESLASHEQUAL 94 | AT 95 | OP 96 | ERRORTOKEN 97 | N_TOKENS 98 | NT_OFFSET 99 | 100 | 101 | .. seealso:: 102 | 103 | Module :mod:`parser` 104 | The second example for the :mod:`parser` module shows how to use the 105 | :mod:`symbol` module. 106 | 107 | -------------------------------------------------------------------------------- /library/tty.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`tty` --- Terminal control functions 3 | ========================================= 4 | 5 | .. module:: tty 6 | :platform: Unix 7 | :synopsis: Utility functions that perform common terminal control operations. 8 | .. moduleauthor:: Steen Lumholt 9 | .. sectionauthor:: Moshe Zadka 10 | 11 | 12 | The :mod:`tty` module defines functions for putting the tty into cbreak and raw 13 | modes. 14 | 15 | Because it requires the :mod:`termios` module, it will work only on Unix. 16 | 17 | The :mod:`tty` module defines the following functions: 18 | 19 | 20 | .. function:: setraw(fd[, when]) 21 | 22 | Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it 23 | defaults to :const:`termios.TCSAFLUSH`, and is passed to 24 | :func:`termios.tcsetattr`. 25 | 26 | 27 | .. function:: setcbreak(fd[, when]) 28 | 29 | Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it 30 | defaults to :const:`termios.TCSAFLUSH`, and is passed to 31 | :func:`termios.tcsetattr`. 32 | 33 | 34 | .. seealso:: 35 | 36 | Module :mod:`termios` 37 | Low-level terminal control interface. 38 | 39 | -------------------------------------------------------------------------------- /library/unix.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _unix: 3 | 4 | ********************** 5 | Unix Specific Services 6 | ********************** 7 | 8 | The modules described in this chapter provide interfaces to features that are 9 | unique to the Unix operating system, or in some cases to some or many variants 10 | of it. Here's an overview: 11 | 12 | 13 | .. toctree:: 14 | 15 | posix.rst 16 | pwd.rst 17 | spwd.rst 18 | grp.rst 19 | crypt.rst 20 | dl.rst 21 | termios.rst 22 | tty.rst 23 | pty.rst 24 | fcntl.rst 25 | pipes.rst 26 | posixfile.rst 27 | resource.rst 28 | nis.rst 29 | syslog.rst 30 | commands.rst 31 | -------------------------------------------------------------------------------- /library/uu.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`uu` --- Encode and decode uuencode files 3 | ============================================== 4 | 5 | .. module:: uu 6 | :synopsis: Encode and decode files in uuencode format. 7 | .. moduleauthor:: Lance Ellinghouse 8 | 9 | 10 | This module encodes and decodes files in uuencode format, allowing arbitrary 11 | binary data to be transferred over ASCII-only connections. Wherever a file 12 | argument is expected, the methods accept a file-like object. For backwards 13 | compatibility, a string containing a pathname is also accepted, and the 14 | corresponding file will be opened for reading and writing; the pathname ``'-'`` 15 | is understood to mean the standard input or output. However, this interface is 16 | deprecated; it's better for the caller to open the file itself, and be sure 17 | that, when required, the mode is ``'rb'`` or ``'wb'`` on Windows. 18 | 19 | .. index:: 20 | single: Jansen, Jack 21 | single: Ellinghouse, Lance 22 | 23 | This code was contributed by Lance Ellinghouse, and modified by Jack Jansen. 24 | 25 | .. seealso:: 26 | 27 | Latest version of the `uu module Python source code 28 | `_ 29 | 30 | The :mod:`uu` module defines the following functions: 31 | 32 | 33 | .. function:: encode(in_file, out_file[, name[, mode]]) 34 | 35 | Uuencode file *in_file* into file *out_file*. The uuencoded file will have the 36 | header specifying *name* and *mode* as the defaults for the results of decoding 37 | the file. The default defaults are taken from *in_file*, or ``'-'`` and ``0666`` 38 | respectively. 39 | 40 | 41 | .. function:: decode(in_file[, out_file[, mode[, quiet]]]) 42 | 43 | This call decodes uuencoded file *in_file* placing the result on file 44 | *out_file*. If *out_file* is a pathname, *mode* is used to set the permission 45 | bits if the file must be created. Defaults for *out_file* and *mode* are taken 46 | from the uuencode header. However, if the file specified in the header already 47 | exists, a :exc:`uu.Error` is raised. 48 | 49 | :func:`decode` may print a warning to standard error if the input was produced 50 | by an incorrect uuencoder and Python could recover from that error. Setting 51 | *quiet* to a true value silences this warning. 52 | 53 | 54 | .. exception:: Error() 55 | 56 | Subclass of :exc:`Exception`, this can be raised by :func:`uu.decode` under 57 | various situations, such as described above, but also including a badly 58 | formatted header, or truncated input file. 59 | 60 | 61 | .. seealso:: 62 | 63 | Module :mod:`binascii` 64 | Support module containing ASCII-to-binary and binary-to-ASCII conversions. 65 | 66 | -------------------------------------------------------------------------------- /library/whichdb.rst: -------------------------------------------------------------------------------- 1 | :mod:`whichdb` --- Guess which DBM module created a database 2 | ============================================================ 3 | 4 | .. module:: whichdb 5 | :synopsis: Guess which DBM-style module created a given database. 6 | 7 | .. note:: 8 | The :mod:`whichdb` module's only function has been put into the :mod:`dbm` 9 | module in Python 3.0. The :term:`2to3` tool will automatically adapt imports 10 | when converting your sources to 3.0. 11 | 12 | 13 | The single function in this module attempts to guess which of the several simple 14 | database modules available--\ :mod:`dbm`, :mod:`gdbm`, or :mod:`dbhash`\ 15 | --should be used to open a given file. 16 | 17 | 18 | .. function:: whichdb(filename) 19 | 20 | Returns one of the following values: ``None`` if the file can't be opened 21 | because it's unreadable or doesn't exist; the empty string (``''``) if the 22 | file's format can't be guessed; or a string containing the required module name, 23 | such as ``'dbm'`` or ``'gdbm'``. 24 | 25 | -------------------------------------------------------------------------------- /library/windows.rst: -------------------------------------------------------------------------------- 1 | .. _mswin-specific-services: 2 | 3 | **************************** 4 | MS Windows Specific Services 5 | **************************** 6 | 7 | This chapter describes modules that are only available on MS Windows platforms. 8 | 9 | 10 | .. toctree:: 11 | 12 | msilib.rst 13 | msvcrt.rst 14 | _winreg.rst 15 | winsound.rst 16 | -------------------------------------------------------------------------------- /library/xml.dom.pulldom.rst: -------------------------------------------------------------------------------- 1 | 2 | :mod:`xml.dom.pulldom` --- Support for building partial DOM trees 3 | ================================================================= 4 | 5 | .. module:: xml.dom.pulldom 6 | :synopsis: Support for building partial DOM trees from SAX events. 7 | .. moduleauthor:: Paul Prescod 8 | 9 | 10 | .. versionadded:: 2.0 11 | 12 | :mod:`xml.dom.pulldom` allows building only selected portions of a Document 13 | Object Model representation of a document from SAX events. 14 | 15 | 16 | .. class:: PullDOM([documentFactory]) 17 | 18 | :class:`xml.sax.handler.ContentHandler` implementation that ... 19 | 20 | 21 | .. class:: DOMEventStream(stream, parser, bufsize) 22 | 23 | ... 24 | 25 | 26 | .. class:: SAX2DOM([documentFactory]) 27 | 28 | :class:`xml.sax.handler.ContentHandler` implementation that ... 29 | 30 | 31 | .. function:: parse(stream_or_string[, parser[, bufsize]]) 32 | 33 | ... 34 | 35 | 36 | .. function:: parseString(string[, parser]) 37 | 38 | ... 39 | 40 | 41 | .. data:: default_bufsize 42 | 43 | Default value for the *bufsize* parameter to :func:`parse`. 44 | 45 | .. versionchanged:: 2.1 46 | The value of this variable can be changed before calling :func:`parse` and the 47 | new value will take effect. 48 | 49 | 50 | .. _domeventstream-objects: 51 | 52 | DOMEventStream Objects 53 | ---------------------- 54 | 55 | 56 | .. method:: DOMEventStream.getEvent() 57 | 58 | ... 59 | 60 | 61 | .. method:: DOMEventStream.expandNode(node) 62 | 63 | ... 64 | 65 | 66 | .. method:: DOMEventStream.reset() 67 | 68 | ... 69 | 70 | -------------------------------------------------------------------------------- /make.bat: -------------------------------------------------------------------------------- 1 | @@echo off 2 | setlocal 3 | 4 | set SVNROOT=http://svn.python.org/projects 5 | if "%PYTHON%" EQU "" set PYTHON=..\pcbuild\python 6 | if "%HTMLHELP%" EQU "" set HTMLHELP=%ProgramFiles%\HTML Help Workshop\hhc.exe 7 | if "%DISTVERSION%" EQU "" for /f "usebackq" %%v in (`%PYTHON% tools/sphinxext/patchlevel.py`) do set DISTVERSION=%%v 8 | 9 | if "%1" EQU "" goto help 10 | if "%1" EQU "html" goto build 11 | if "%1" EQU "htmlhelp" goto build 12 | if "%1" EQU "latex" goto build 13 | if "%1" EQU "text" goto build 14 | if "%1" EQU "suspicious" goto build 15 | if "%1" EQU "linkcheck" goto build 16 | if "%1" EQU "changes" goto build 17 | if "%1" EQU "checkout" goto checkout 18 | if "%1" EQU "update" goto update 19 | 20 | :help 21 | set this=%~n0 22 | echo HELP 23 | echo. 24 | echo %this% checkout 25 | echo %this% update 26 | echo %this% html 27 | echo %this% htmlhelp 28 | echo %this% latex 29 | echo %this% text 30 | echo %this% suspicious 31 | echo %this% linkcheck 32 | echo %this% changes 33 | echo. 34 | goto end 35 | 36 | :checkout 37 | svn co %SVNROOT%/external/Sphinx-0.6.7/sphinx tools/sphinx 38 | svn co %SVNROOT%/external/docutils-0.6/docutils tools/docutils 39 | svn co %SVNROOT%/external/Jinja-2.3.1/jinja2 tools/jinja2 40 | svn co %SVNROOT%/external/Pygments-1.3.1/pygments tools/pygments 41 | goto end 42 | 43 | :update 44 | svn update tools/sphinx 45 | svn update tools/docutils 46 | svn update tools/jinja2 47 | svn update tools/pygments 48 | goto end 49 | 50 | :build 51 | if not exist build mkdir build 52 | if not exist build\%1 mkdir build\%1 53 | if not exist build\doctrees mkdir build\doctrees 54 | cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%* 55 | if "%1" EQU "htmlhelp" "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp 56 | goto end 57 | 58 | :end 59 | -------------------------------------------------------------------------------- /net-api/extending.rst: -------------------------------------------------------------------------------- 1 | .. highlightlang:: c 2 | 3 | 4 | .. _extending-intro: 5 | 6 | ****************************** 7 | Extending IronPython with C# 8 | ****************************** 9 | 10 | 11 | 12 | .. _extending-simpleexample: 13 | 14 | A Simple Example 15 | ================ 16 | 17 | -------------------------------------------------------------------------------- /net-api/index.rst: -------------------------------------------------------------------------------- 1 | .. _extending-index: 2 | 3 | ################################################## 4 | IronPython .NET API Reference Manual 5 | ################################################## 6 | 7 | This section includes documentation on low-level IronPython APIs that are available for 8 | extending IronPython and providing deep integration with other .NET applications. 9 | 10 | .. toctree:: 11 | :maxdepth: 2 12 | :numbered: 13 | 14 | netmodules.rst 15 | extending.rst 16 | parsing.rst 17 | -------------------------------------------------------------------------------- /net-api/parsing.rst: -------------------------------------------------------------------------------- 1 | .. highlightlang:: c 2 | 3 | 4 | .. _extending-parsing: 5 | 6 | ********************** 7 | Parsing and Tokenizing 8 | ********************** 9 | 10 | .. ctype: Parser() 11 | 12 | The Parser class has no public constructors. To create a Parser call the Parser.CreateParser factory method. 13 | 14 | .. cfunction:: Parser CreateParser(CompilerContext context, PythonOptions options) 15 | 16 | Creates a new parser using the given compiler context and options. 17 | 18 | .. cfunction:: PythonAst ParseFile(bool makeModule) 19 | .. cfunction:: PythonAst ParseFile(bool makeModule, bool returnValue) 20 | 21 | .. cfunction:: PythonAst ParseInteractiveCode(out ScriptCodeParseResult properties) 22 | 23 | Parse one or more lines of interactive input 24 | 25 | Returns null if input is not yet valid but could be with more lines 26 | 27 | .. cfunction:: PythonAst ParseSingleStatement() 28 | .. cfunction:: PythonAst ParseTopExpression() 29 | 30 | .. cfunction:: static int GetNextAutoIndentSize(string text, int autoIndentTabWidth) 31 | 32 | Given the interactive text input for a compound statement, calculate what the indentation level of the next line should be 33 | 34 | .. cfunction:: ErrorSink ErrorSink { get; set; } 35 | .. cfunction:: ParserSink ParserSink { get; set; } 36 | .. cfunction:: public int ErrorCode { get; } 37 | .. cfunction:: void Reset(SourceUnit sourceUnit, ModuleOptions languageFeatures) 38 | .. cfunction:: void Reset() 39 | .. cfunction:: void Dispose() 40 | -------------------------------------------------------------------------------- /reference/grammar.rst: -------------------------------------------------------------------------------- 1 | Full Grammar specification 2 | ========================== 3 | 4 | This is the full Python grammar, as it is read by the parser generator and used 5 | to parse Python source files: 6 | 7 | .. literalinclude:: ../../Grammar/Grammar 8 | -------------------------------------------------------------------------------- /reference/index.rst: -------------------------------------------------------------------------------- 1 | .. _reference-index: 2 | 3 | ################################# 4 | The Python Language Reference 5 | ################################# 6 | 7 | :Release: |version| 8 | :Date: |today| 9 | 10 | This reference manual describes the syntax and "core semantics" of the 11 | language. It is terse, but attempts to be exact and complete. The semantics of 12 | non-essential built-in object types and of the built-in functions and modules 13 | are described in :ref:`library-index`. For an informal introduction to the 14 | language, see :ref:`tutorial-index`. For C or C++ programmers, two additional 15 | manuals exist: :ref:`extending-index` describes the high-level picture of how to 16 | write a Python extension module, and the :ref:`c-api-index` describes the 17 | interfaces available to C/C++ programmers in detail. 18 | 19 | .. toctree:: 20 | :maxdepth: 2 21 | :numbered: 22 | 23 | introduction.rst 24 | lexical_analysis.rst 25 | datamodel.rst 26 | executionmodel.rst 27 | expressions.rst 28 | simple_stmts.rst 29 | compound_stmts.rst 30 | toplevel_components.rst 31 | grammar.rst 32 | -------------------------------------------------------------------------------- /tools/dailybuild.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Runs the daily build of the Python docs on dinsdale.python.org. 5 | # 6 | # Usages: 7 | # 8 | # dailybuild.py 9 | # 10 | # without any arguments builds docs for all branches configured in the global 11 | # BRANCHES value. 12 | # 13 | # dailybuild.py [-d] 14 | # 15 | # builds one version, where is an SVN checkout directory of the 16 | # Python branch to build docs for, and is the directory where the 17 | # result should be placed. If -d is given, the docs are built even if the 18 | # branch is in development mode (i.e. version contains a, b or c). 19 | # 20 | # This script is not run from the checkout, so if you want to change how the 21 | # daily build is run, you must replace it on dinsdale. This is necessary, for 22 | # example, after the release of a new minor version. 23 | # 24 | # 03/2010, Georg Brandl 25 | 26 | import os 27 | import sys 28 | import getopt 29 | 30 | 31 | BUILDROOT = '/home/gbrandl/docbuild' 32 | WWWROOT = '/data/ftp.python.org/pub/docs.python.org' 33 | 34 | BRANCHES = [ 35 | # checkout, target, isdev 36 | (BUILDROOT + '/python33', WWWROOT + '/dev', True), 37 | (BUILDROOT + '/python27', WWWROOT, False), 38 | (BUILDROOT + '/python32', WWWROOT + '/py3k', False), 39 | ] 40 | 41 | 42 | def build_one(checkout, target, isdev): 43 | print 'Doc autobuild started in %s' % checkout 44 | os.chdir(checkout) 45 | print 'Running svn update' 46 | os.system('svn update') 47 | print 'Running make autobuild' 48 | if os.WEXITSTATUS(os.system( 49 | 'cd Doc; make autobuild-%s' % (isdev and 'dev' or 'stable'))) == 2: 50 | print '*' * 80 51 | return 52 | print 'Copying HTML files' 53 | os.system('cp -a Doc/build/html/* %s' % target) 54 | print 'Copying dist files' 55 | os.system('mkdir -p %s/archives' % target) 56 | os.system('cp -a Doc/dist/* %s/archives' % target) 57 | print 'Finished' 58 | print '=' * 80 59 | 60 | def usage(): 61 | print 'Usage:' 62 | print ' %s' % sys.argv[0] 63 | print 'or' 64 | print ' %s [-d] ' % sys.argv[0] 65 | sys.exit(1) 66 | 67 | 68 | if __name__ == '__main__': 69 | try: 70 | opts, args = getopt.getopt(sys.argv[1:], 'd') 71 | except getopt.error: 72 | usage() 73 | if opts and not args: 74 | usage() 75 | if args: 76 | if len(args) != 2: 77 | usage() 78 | build_one(args[0], args[1], bool(opts)) 79 | else: 80 | for branch in BRANCHES: 81 | build_one(*branch) 82 | -------------------------------------------------------------------------------- /tools/roman.py: -------------------------------------------------------------------------------- 1 | """Convert to and from Roman numerals""" 2 | 3 | __author__ = "Mark Pilgrim (f8dy@diveintopython.org)" 4 | __version__ = "1.4" 5 | __date__ = "8 August 2001" 6 | __copyright__ = """Copyright (c) 2001 Mark Pilgrim 7 | 8 | This program is part of "Dive Into Python", a free Python tutorial for 9 | experienced programmers. Visit http://diveintopython.org/ for the 10 | latest version. 11 | 12 | This program is free software; you can redistribute it and/or modify 13 | it under the terms of the Python 2.1.1 license, available at 14 | http://www.python.org/2.1.1/license.html 15 | """ 16 | 17 | import re 18 | 19 | #Define exceptions 20 | class RomanError(Exception): pass 21 | class OutOfRangeError(RomanError): pass 22 | class NotIntegerError(RomanError): pass 23 | class InvalidRomanNumeralError(RomanError): pass 24 | 25 | #Define digit mapping 26 | romanNumeralMap = (('M', 1000), 27 | ('CM', 900), 28 | ('D', 500), 29 | ('CD', 400), 30 | ('C', 100), 31 | ('XC', 90), 32 | ('L', 50), 33 | ('XL', 40), 34 | ('X', 10), 35 | ('IX', 9), 36 | ('V', 5), 37 | ('IV', 4), 38 | ('I', 1)) 39 | 40 | def toRoman(n): 41 | """convert integer to Roman numeral""" 42 | if not (0 < n < 5000): 43 | raise OutOfRangeError("number out of range (must be 1..4999)") 44 | if int(n) != n: 45 | raise NotIntegerError("decimals can not be converted") 46 | 47 | result = "" 48 | for numeral, integer in romanNumeralMap: 49 | while n >= integer: 50 | result += numeral 51 | n -= integer 52 | return result 53 | 54 | #Define pattern to detect valid Roman numerals 55 | romanNumeralPattern = re.compile(""" 56 | ^ # beginning of string 57 | M{0,4} # thousands - 0 to 4 M's 58 | (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), 59 | # or 500-800 (D, followed by 0 to 3 C's) 60 | (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), 61 | # or 50-80 (L, followed by 0 to 3 X's) 62 | (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), 63 | # or 5-8 (V, followed by 0 to 3 I's) 64 | $ # end of string 65 | """ ,re.VERBOSE) 66 | 67 | def fromRoman(s): 68 | """convert Roman numeral to integer""" 69 | if not s: 70 | raise InvalidRomanNumeralError('Input can not be blank') 71 | if not romanNumeralPattern.search(s): 72 | raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s) 73 | 74 | result = 0 75 | index = 0 76 | for numeral, integer in romanNumeralMap: 77 | while s[index:index+len(numeral)] == numeral: 78 | result += integer 79 | index += len(numeral) 80 | return result 81 | -------------------------------------------------------------------------------- /tools/sphinx-build.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Sphinx - Python documentation toolchain 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | :copyright: 2007-2010 by Georg Brandl. 7 | :license: Python license. 8 | """ 9 | 10 | import sys 11 | import warnings 12 | 13 | # Get rid of UserWarnings reported by pkg_resources. 14 | warnings.filterwarnings('ignore', category=UserWarning, module='jinja2') 15 | 16 | if __name__ == '__main__': 17 | 18 | if sys.version_info[:3] < (2, 4, 0): 19 | print >>sys.stderr, """\ 20 | Error: Sphinx needs to be executed with Python 2.4 or newer 21 | (If you run this from the Makefile, you can set the PYTHON variable 22 | to the path of an alternative interpreter executable, e.g., 23 | ``make html PYTHON=python2.5``). 24 | """ 25 | sys.exit(1) 26 | 27 | from sphinx import main 28 | sys.exit(main(sys.argv)) 29 | -------------------------------------------------------------------------------- /tools/sphinxext/download.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | {% set title = 'Download' %} 3 | {% if daily is defined %} 4 | {% set dlbase = pathto('archives', 1) %} 5 | {% else %} 6 | {% set dlbase = 'http://docs.python.org/ftp/python/doc/' + release %} 7 | {% endif %} 8 | 9 | {% block body %} 10 |

    Download Python {{ release }} Documentation

    11 | 12 | {% if last_updated %}

    Last updated on: {{ last_updated }}.

    {% endif %} 13 | 14 |

    To download an archive containing all the documents for this version of 15 | Python in one of various formats, follow one of links in this table. The numbers 16 | in the table are the size of the download files in megabytes.

    17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 |
    FormatPacked as .zipPacked as .tar.bz2
    PDF (US-Letter paper size)Download (ca. 8 MB)Download (ca. 8 MB)
    PDF (A4 paper size)Download (ca. 8 MB)Download (ca. 8 MB)
    HTMLDownload (ca. 6 MB)Download (ca. 4 MB)
    Plain TextDownload (ca. 2 MB)Download (ca. 1.5 MB)
    37 | 38 | 39 |

    These archives contain all the content in the documentation.

    40 | 41 |

    Unpacking

    42 | 43 |

    Unix users should download the .tar.bz2 archives; these are bzipped tar 44 | archives and can be handled in the usual way using tar and the bzip2 45 | program. The InfoZIP unzip program can be 46 | used to handle the ZIP archives if desired. The .tar.bz2 archives provide the 47 | best compression and fastest download times.

    48 | 49 |

    Windows users can use the ZIP archives since those are customary on that 50 | platform. These are created on Unix using the InfoZIP zip program.

    51 | 52 | 53 |

    Problems

    54 | 55 |

    If you have comments or suggestions for the Python documentation, please send 56 | email to docs@python.org.

    57 | {% endblock %} 58 | -------------------------------------------------------------------------------- /tools/sphinxext/indexsidebar.html: -------------------------------------------------------------------------------- 1 |

    Download

    2 |

    Download these documents

    3 |

    Docs for other versions

    4 | 10 | 11 |

    Other resources

    12 | 24 | -------------------------------------------------------------------------------- /tools/sphinxext/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | {% block rootrellink %} 3 |
  • 5 |
  • {{ shorttitle }}{{ reldelim1 }}
  • 6 | {% endblock %} 7 | {% block extrahead %} 8 | 9 | {{ super() }} 10 | {% endblock %} 11 | {% block footer %} 12 | 23 | {% endblock %} 24 | {% block sidebarsourcelink %} 25 | {%- if show_source and has_source and sourcename %} 26 |

    {{ _('This Page') }}

    27 | 32 | {%- endif %} 33 | {% endblock %} 34 | -------------------------------------------------------------------------------- /tools/sphinxext/opensearch.xml: -------------------------------------------------------------------------------- 1 | {% extends "!opensearch.xml" %} 2 | {% block extra -%} 3 | http://www.python.org/images/favicon16x16.ico 4 | {%- endblock %} 5 | -------------------------------------------------------------------------------- /tools/sphinxext/patchlevel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | patchlevel.py 4 | ~~~~~~~~~~~~~ 5 | 6 | Extract version info from Include/patchlevel.h. 7 | Adapted from Doc/tools/getversioninfo. 8 | 9 | :copyright: 2007-2008 by Georg Brandl. 10 | :license: Python license. 11 | """ 12 | 13 | import os 14 | import re 15 | import sys 16 | 17 | def get_header_version_info(srcdir): 18 | patchlevel_h = os.path.join(srcdir, '..', 'Include', 'patchlevel.h') 19 | 20 | # This won't pick out all #defines, but it will pick up the ones we 21 | # care about. 22 | rx = re.compile(r'\s*#define\s+([a-zA-Z][a-zA-Z_0-9]*)\s+([a-zA-Z_0-9]+)') 23 | 24 | d = {} 25 | f = open(patchlevel_h) 26 | try: 27 | for line in f: 28 | m = rx.match(line) 29 | if m is not None: 30 | name, value = m.group(1, 2) 31 | d[name] = value 32 | finally: 33 | f.close() 34 | 35 | release = version = '%s.%s' % (d['PY_MAJOR_VERSION'], d['PY_MINOR_VERSION']) 36 | micro = int(d['PY_MICRO_VERSION']) 37 | if micro != 0: 38 | release += '.' + str(micro) 39 | 40 | level = d['PY_RELEASE_LEVEL'] 41 | suffixes = { 42 | 'PY_RELEASE_LEVEL_ALPHA': 'a', 43 | 'PY_RELEASE_LEVEL_BETA': 'b', 44 | 'PY_RELEASE_LEVEL_GAMMA': 'rc', 45 | } 46 | if level != 'PY_RELEASE_LEVEL_FINAL': 47 | release += suffixes[level] + str(int(d['PY_RELEASE_SERIAL'])) 48 | return version, release 49 | 50 | 51 | def get_sys_version_info(): 52 | major, minor, micro, level, serial = sys.version_info 53 | release = version = '%s.%s' % (major, minor) 54 | if micro: 55 | release += '.%s' % micro 56 | if level != 'final': 57 | release += '%s%s' % (level[0], serial) 58 | return version, release 59 | 60 | 61 | def get_version_info(): 62 | try: 63 | return get_header_version_info('.') 64 | except (IOError, OSError): 65 | version, release = get_sys_version_info() 66 | print >>sys.stderr, 'Can\'t get version info from Include/patchlevel.h, ' \ 67 | 'using version of this interpreter (%s).' % release 68 | return version, release 69 | 70 | if __name__ == '__main__': 71 | print get_header_version_info('.')[1] 72 | -------------------------------------------------------------------------------- /tools/sphinxext/static/py.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IronLanguages/ironpython-docs/5e7a892ad46ae374bf85af45c093ad1ecb49fbbb/tools/sphinxext/static/py.png -------------------------------------------------------------------------------- /tutorial/index.rst: -------------------------------------------------------------------------------- 1 | .. _tutorial-index: 2 | 3 | ###################### 4 | The Python Tutorial 5 | ###################### 6 | 7 | :Release: |version| 8 | :Date: |today| 9 | 10 | Python is an easy to learn, powerful programming language. It has efficient 11 | high-level data structures and a simple but effective approach to 12 | object-oriented programming. Python's elegant syntax and dynamic typing, 13 | together with its interpreted nature, make it an ideal language for scripting 14 | and rapid application development in many areas on most platforms. 15 | 16 | The Python interpreter and the extensive standard library are freely available 17 | in source or binary form for all major platforms from the Python Web site, 18 | http://www.python.org/, and may be freely distributed. The same site also 19 | contains distributions of and pointers to many free third party Python modules, 20 | programs and tools, and additional documentation. 21 | 22 | The Python interpreter is easily extended with new functions and data types 23 | implemented in C or C++ (or other languages callable from C). Python is also 24 | suitable as an extension language for customizable applications. 25 | 26 | This tutorial introduces the reader informally to the basic concepts and 27 | features of the Python language and system. It helps to have a Python 28 | interpreter handy for hands-on experience, but all examples are self-contained, 29 | so the tutorial can be read off-line as well. 30 | 31 | For a description of standard objects and modules, see :ref:`library-index`. 32 | :ref:`reference-index` gives a more formal definition of the language. To write 33 | extensions in C or C++, read :ref:`extending-index` and 34 | :ref:`c-api-index`. There are also several books covering Python in depth. 35 | 36 | This tutorial does not attempt to be comprehensive and cover every single 37 | feature, or even every commonly used feature. Instead, it introduces many of 38 | Python's most noteworthy features, and will give you a good idea of the 39 | language's flavor and style. After reading it, you will be able to read and 40 | write Python modules and programs, and you will be ready to learn more about the 41 | various Python library modules described in :ref:`library-index`. 42 | 43 | The :ref:`glossary` is also worth going through. 44 | 45 | .. toctree:: 46 | :numbered: 47 | 48 | appetite.rst 49 | interpreter.rst 50 | introduction.rst 51 | controlflow.rst 52 | datastructures.rst 53 | modules.rst 54 | inputoutput.rst 55 | errors.rst 56 | classes.rst 57 | stdlib.rst 58 | stdlib2.rst 59 | whatnow.rst 60 | interactive.rst 61 | floatingpoint.rst 62 | -------------------------------------------------------------------------------- /using/index.rst: -------------------------------------------------------------------------------- 1 | .. _using-index: 2 | 3 | ########################## 4 | Python Setup and Usage 5 | ########################## 6 | 7 | 8 | This part of the documentation is devoted to general information on the setup 9 | of the Python environment on different platform, the invocation of the 10 | interpreter and things that make working with Python easier. 11 | 12 | 13 | .. toctree:: 14 | :numbered: 15 | 16 | cmdline.rst 17 | unix.rst 18 | windows.rst 19 | mac.rst 20 | 21 | -------------------------------------------------------------------------------- /whatsnew/index.rst: -------------------------------------------------------------------------------- 1 | .. _whatsnew-index: 2 | 3 | ###################### 4 | What's New in Python 5 | ###################### 6 | 7 | The "What's New in Python" series of essays takes tours through the most 8 | important changes between major Python versions. They are a "must read" for 9 | anyone wishing to stay up-to-date after a new release. 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 2.7.rst 15 | 2.6.rst 16 | 2.5.rst 17 | 2.4.rst 18 | 2.3.rst 19 | 2.2.rst 20 | 2.1.rst 21 | 2.0.rst 22 | --------------------------------------------------------------------------------