From 6b39dd5920a982a52ce3ca8f2b45094ec471acd6 Mon Sep 17 00:00:00 2001 From: Thomas Kluyver Date: Tue, 17 Sep 2013 12:06:14 -0700 Subject: Start moving docs to reST --- .gitignore | 1 + doc/Makefile | 153 ++++++++++++++++++++++++++++++++++ doc/conf.py | 246 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ doc/index.rst | 42 ++++++++++ doc/install.rst | 22 +++++ doc/make.bat | 190 ++++++++++++++++++++++++++++++++++++++++++ doc/overview.rst | 238 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 892 insertions(+) create mode 100644 doc/Makefile create mode 100644 doc/conf.py create mode 100644 doc/index.rst create mode 100644 doc/install.rst create mode 100644 doc/make.bat create mode 100644 doc/overview.rst diff --git a/.gitignore b/.gitignore index 0d20b64..3341044 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.pyc +doc/_build diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 0000000..ced8a68 --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Pexpect.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Pexpect.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/Pexpect" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Pexpect" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/doc/conf.py b/doc/conf.py new file mode 100644 index 0000000..84c5ab2 --- /dev/null +++ b/doc/conf.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- +# +# Pexpect documentation build configuration file, created by +# sphinx-quickstart on Tue Sep 17 11:05:11 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Pexpect' +copyright = u'2013, Noah Spurrier and contributors' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '2.9' +# The full version, including alpha/beta/rc tags. +release = '2.9' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Pexpectdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'Pexpect.tex', u'Pexpect Documentation', + u'Noah Spurrier and contributors', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'pexpect', u'Pexpect Documentation', + [u'Noah Spurrier and contributors'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'Pexpect', u'Pexpect Documentation', + u'Noah Spurrier and contributors', 'Pexpect', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/doc/index.rst b/doc/index.rst new file mode 100644 index 0000000..bc6f4ff --- /dev/null +++ b/doc/index.rst @@ -0,0 +1,42 @@ +Pexpected version |version| +=========================== + +Pexpected is a Unicode-aware, Python 3 compatible fork of Pexpect, a pure Python +Expect-like module. + +Pexpect makes Python a better tool for controlling other +applications. + +Pexpect is a pure Python module for spawning child applications; +controlling them; and responding to expected patterns in their output. +Pexpect works like Don Libes' Expect. Pexpect allows your script to +spawn a child application and control it as if a human were typing +commands. + +Pexpect can be used for automating interactive applications such as +ssh, ftp, passwd, telnet, etc. It can be used to a automate setup +scripts for duplicating software package installations on different +servers. It can be used for automated software testing. Pexpect is in +the spirit of Don Libes' Expect, but Pexpect is pure Python. Unlike +other Expect-like modules for Python, Pexpect does not require TCL or +Expect nor does it require C extensions to be compiled. It should work +on any platform that supports the standard Python pty module. The +Pexpect interface was designed to be easy to use. + +Contents: + +.. toctree:: + :maxdepth: 2 + + install + overview + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/doc/install.rst b/doc/install.rst new file mode 100644 index 0000000..081ed55 --- /dev/null +++ b/doc/install.rst @@ -0,0 +1,22 @@ +Installation +============ + +Pexpected is on PyPI, and can be installed with standard tools:: + + pip install pexpected + +Or:: + + easy_install pexpected + +Note that the name is 'pexpected' for installation, but 'pexpect' for imports. + +Requirements +------------ + +Pexpected requires Python 2.6 or 3.2 or above. For older versions of Python, +continue using Pexpect. + +Pexpected (and Pexpect) only work on POSIX systems, where the :mod:`pty` module +is present in the standard library. It may be possible to run it on Windows +using `Cygwin `_. \ No newline at end of file diff --git a/doc/make.bat b/doc/make.bat new file mode 100644 index 0000000..448f147 --- /dev/null +++ b/doc/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Pexpect.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Pexpect.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/doc/overview.rst b/doc/overview.rst new file mode 100644 index 0000000..83d1899 --- /dev/null +++ b/doc/overview.rst @@ -0,0 +1,238 @@ +API Overview +============ + +Pexpect can be used for automating interactive applications such as ssh, ftp, +mencoder, passwd, etc. The Pexpect interface was designed to be easy to use. + +Here is an example of Pexpect in action:: + + # This connects to the openbsd ftp site and + # downloads the recursive directory listing. + import pexpect + child = pexpect.spawn('ftp ftp.openbsd.org') + child.expect('Name .*: ') + child.sendline('anonymous') + child.expect('Password:') + child.sendline('noah@example.com') + child.expect('ftp> ') + child.sendline('cd pub') + child.expect('ftp> ') + child.sendline('get ls-lR.gz') + child.expect('ftp> ') + child.sendline('bye') + +Obviously you could write an ftp client using Python's own :mod:`ftplib` module, +but this is just a demonstration. You can use this technique with any application. +This is especially handy if you are writing automated test tools. + +There are two important methods in Pexpect -- :meth:`~pexpect.spawn.expect` and +:meth:`~pexpect.spawn.send` (or :meth:`~pexpect.spawn.sendline` which is +like :meth:`~pexpect.spawn.send` with a linefeed). The :meth:`~pexpect.spawn.expect` +method waits for the child application to return a given string. The string you +specify is a regular expression, so you can match complicated patterns. The +:meth:`~pexpect.spawn.send` method writes a string to the child application. +From the child's point of view it looks just like someone typed the text from a +terminal. After each call to :meth:`~pexpect.spawn.expect` the before and after +properties will be set to the text printed by child application. The before +property will contain all text up to the expected string pattern. The after +string will contain the text that was matched by the expected pattern. +The match property is set to the `re match object `_. + +An example of Pexpect in action may make things more clear. This example uses +ftp to login to the OpenBSD site; list files in a directory; and then pass +interactive control of the ftp session to the human user:: + + import pexpect + child = pexpect.spawn ('ftp ftp.openbsd.org') + child.expect ('Name .*: ') + child.sendline ('anonymous') + child.expect ('Password:') + child.sendline ('noah@example.com') + child.expect ('ftp> ') + child.sendline ('ls /pub/OpenBSD/') + child.expect ('ftp> ') + print child.before # Print the result of the ls command. + child.interact() # Give control of the child to the user. + +Special EOF and TIMEOUT patterns +-------------------------------- + +There are two special patterns to match the End Of File (:class:`~pexpect.EOF`) +or a Timeout condition (:class:`~pexpect.TIMEOUT`). You you can pass these +patterns to :meth:`~pexpect.spawn.expect`. These patterns are not regular +expressions. Use them like predefined constants. + +If the child has died and you have read all the child's output then ordinarily +:meth:`~pexpect.spawn.expect` will raise an :class:`~pexpect.EOF` exception. +You can read everything up to the EOF without generating an exception by using +the EOF pattern expect. In this case everything the child has output will be +available in the before property. + +The pattern given to :meth:`~pexpect.spawn.expect` may be a regular expression +or it may also be a list of regular expressions. This allows you to match +multiple optional responses. The :meth:`~pexpect.spawn.expect` method returns +the index of the pattern that was matched. For example, say you wanted to login +to a server. After entering a password you could get various responses from the +server -- your password could be rejected; or you could be allowed in and asked +for your terminal type; or you could be let right in and given a command prompt. +The following code fragment gives an example of this:: + + child.expect('password:') + child.sendline(my_secret_password) + # We expect any of these three patterns... + i = child.expect (['Permission denied', 'Terminal type', '[#\$] ']) + if i==0: + print('Permission denied on host. Can't login') + child.kill(0) + elif i==2: + print('Login OK... need to send terminal type.') + child.sendline('vt100') + child.expect('[#\$] ') + elif i==3: + print('Login OK.') + print('Shell command prompt', child.after) + +If nothing matches an expected pattern then :meth:`~pexpect.spawn.expect` will +eventually raise a :class:`~pexpect.TIMEOUT` exception. The default time is 30 +seconds, but you can change this by passing a timeout argument to +:meth:`~pexpect.spawn.expect`:: + + # Wait no more than 2 minutes (120 seconds) for password prompt. + child.expect('password:', timeout=120) + +Find the end of line -- CR/LF conventions +----------------------------------------- + +Pexpect matches regular expressions a little differently than what you might be +used to. + +The :regexp:`$` pattern for end of line match is useless. The :regexp:`$` +matches the end of string, but Pexpect reads from the child one character at a +time, so each character looks like the end of a line. Pexpect can't do a +look-ahead into the child's output stream. In general you would have this +situation when using regular expressions with any stream. + +.. note:: + + Pexpect does have an internal buffer, so reads are faster than one character + at a time, but from the user's perspective the regex patterns test happens + one character at a time. + +The best way to match the end of a line is to look for the newline: ``"\r\n"`` +(CR/LF). Yes, that does appear to be DOS-style. It may surprise some UNIX people +to learn that terminal TTY device drivers (dumb, vt100, ANSI, xterm, etc.) all +use the CR/LF combination to signify the end of line. Pexpect uses a Pseudo-TTY +device to talk to the child application, so when the child app prints ``"\n"`` +you actually see ``"\r\n"``. + +UNIX uses just linefeeds to end lines of text, but not when it comes to TTY +devices! TTY devices are more like the Windows world. Each line of text ends +with a CR/LF combination. When you intercept data from a UNIX command from a +TTY device you will find that the TTY device outputs a CR/LF combination. A +UNIX command may only write a linefeed (``\n``), but the TTY device driver +converts it to CR/LF. This means that your terminal will see lines end with +CR/LF (hex ``0D 0A``). Since Pexpect emulates a terminal, to match ends of +lines you have to expect the CR/LF combination:: + + child.expect('\r\n') + +If you just need to skip past a new line then ``expect('\n')`` by itself will +work, but if you are expecting a specific pattern before the end of line then +you need to explicitly look for the ``\r``. For example the following expects a +word at the end of a line:: + + child.expect('\w+\r\n') + +But the following would both fail:: + + child.expect('\w+\n') + +And as explained before, trying to use :regexp:`$` to match the end of line +would not work either:: + + child.expect ('\w+$') + +So if you need to explicitly look for the END OF LINE, you want to look for the +CR/LF combination -- not just the LF and not the $ pattern. + +This problem is not limited to Pexpect. This problem happens any time you try +to perform a regular expression match on a stream. Regular expressions need to +look ahead. With a stream it is hard to look ahead because the process +generating the stream may not be finished. There is no way to know if the +process has paused momentarily or is finished and waiting for you. Pexpect must +implicitly always do a NON greedy match (minimal) at the end of a input. + +Pexpect compiles all regular expressions with the :data:`re.DOTALL` flag. +With the :data:`~re.DOTALL` flag, a ``"."`` will match a newline. + +Beware of + and * at the end of patterns +---------------------------------------- + +Remember that any time you try to match a pattern that needs look-ahead that +you will always get a minimal match (non greedy). For example, the following +will always return just one character:: + + child.expect ('.+') + +This example will match successfully, but will always return no characters:: + + child.expect ('.*') + +Generally any star * expression will match as little as possible. + +One thing you can do is to try to force a non-ambiguous character at the end of +your :regexp:`\\d+` pattern. Expect that character to delimit the string. For +example, you might try making the end of your pattrn be :regexp:`\\D+` instead +of :regexp:`\\D*`. Number digits alone would not satisfy the :regexp:`(\\d+)\\D+` +pattern. You would need some numbers and at least one non-number at the end. + + +Debugging +--------- + +If you get the string value of a :class:`pexpect.spawn` object you will get lots +of useful debugging information. For debugging it's very useful to use the +following pattern:: + + try: + i = child.expect ([pattern1, pattern2, pattern3, etc]) + except: + print("Exception was thrown") + print("debug information:") + print(str(child)) + +It is also useful to log the child's input and out to a file or the screen. The +following will turn on logging and send output to stdout (the screen):: + + child = pexpect.spawn(foo) + child.logfile = sys.stdout + +Exceptions +---------- + +:class:`~pexpect.EOF` + +Note that two flavors of EOF Exception may be thrown. They are virtually +identical except for the message string. For practical purposes you should have +no need to distinguish between them, but they do give a little extra information +about what type of platform you are running. The two messages are: + +- "End Of File (EOF) in read(). Exception style platform." +- "End Of File (EOF) in read(). Empty string style platform." + +Some UNIX platforms will throw an exception when you try to read from a file +descriptor in the EOF state. Other UNIX platforms instead quietly return an +empty string to indicate that the EOF state has been reached. + +If you wish to read up to the end of the child's output without generating an +:class:`~pexpect.EOF` exception then use the ``expect(pexpect.EOF)`` method. + +:class:`~pexpect.TIMEOUT` + +The :meth:`~pexpect.spawn.expect` and :meth:`~pexpect.spawn.read` methods will +also timeout if the child does not generate any output for a given amount of +time. If this happens they will raise a :class:`~pexpect.TIMEOUT` exception. +You can have these method ignore a timeout and block indefinitely by passing +``None`` for the timeout parameter:: + + child.expect(pexpect.EOF, timeout=None) -- cgit v1.2.1