% \iffalse meta-comment % % Copyright (C) 2012-2013 by Geoffrey M. Poore % --------------------------------------------------------------------------- % This work may be distributed and/or modified under the % conditions of the LaTeX Project Public License, either version 1.3 % of this license or (at your option) any later version. % The latest version of this license is in % http://www.latex-project.org/lppl.txt % and version 1.3 or later is part of all distributions of LaTeX % version 2005/12/01 or later. % % This work has the LPPL maintenance status `maintained'. % % The Current Maintainer of this work is Geoffrey M. Poore. % % This work consists of the files pythontex.dtx and pythontex.ins % and the derived filebase pythontex.sty. % % \fi % % \iffalse %<*driver> \ProvidesFile{pythontex.dtx} % %\NeedsTeXFormat{LaTeX2e}[1999/12/01] %\ProvidesPackage{pythontex} %<*package> [2013/04/30 Version~0.12] % % %<*driver> \documentclass{ltxdoc} \makeatletter \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{textcomp} \usepackage[svgnames]{xcolor} \usepackage{environ} \usepackage{enumitem} \usepackage[fixlr=false]{pythontex} %Need fixlr=false so can demo issue \usepackage{hyperref} \hypersetup{colorlinks=true,urlcolor=Green,linkcolor=blue} \newcommand{\pytxtodo}[1]{} %\newcommand{\pytxtodo}[1]{\textcolor{red}{TO~DO: \scantokens{#1}}} \newcommand{\changestext}{} \NewEnviron{changelog}[2]{% \g@addto@macro\changestext{\item[#1] (#2) \begin{itemize}}% \expandafter\g@addto@macro\expandafter\changestext\expandafter{\BODY}% \g@addto@macro\changestext{\end{itemize}}% } \newcommand{\PrintChangelog}{% \addcontentsline{toc}{section}{Version History} \section*{Version History}% \begin{description}% \changestext \end{description}% } \EnableCrossrefs \CodelineIndex %\RecordChanges \makeatother \begin{document} \DocInput{pythontex.dtx} %\PrintChanges \PrintIndex \end{document} % % \fi % % \CheckSum{2760} % % \CharacterTable % {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z % Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z % Digits \0\1\2\3\4\5\6\7\8\9 % Exclamation \! Double quote \" Hash (number) \# % Dollar \$ Percent \% Ampersand \& % Acute accent \' Left paren \( Right paren \) % Asterisk \* Plus \+ Comma \, % Minus \- Point \. Solidus \/ % Colon \: Semicolon \; Less than \< % Equals \= Greater than \> Question mark \? % Commercial at \@ Left bracket \[ Backslash \\ % Right bracket \] Circumflex \^ Underscore \_ % Grave accent \` Left brace \{ Vertical bar \| % Right brace \} Tilde \~} % % % \begin{changelog}{v0.12}{2013/05/05} % \item Increased compatibilty with latexmk by providing warnings on not found files. % \end{changelog} % % \begin{changelog}{v0.11}{2013/04/21} % \item As the first non-beta release, this version adds several features and introduces several changes. You should read these release notes carefully, since some changes are not backwards-compatible. Changes are based on a thorough review of all current and planned features. PythonTeX's capabilities have already grown beyond what was originally intended, and a long list of features still remains to be implemented. As a result, some changes are needed to ensure consistent syntax and naming in the future. Insofar as possible, all command names and syntax will be frozen after this release. % \item Added the \texttt{pythontex.py} and \texttt{depythontex.py} wrapper scripts. When run, these detect the current version of Python and import the correct PythonTeX code. It is still possible to run \texttt{pythontex*.py} and \texttt{depythontex*.py} directly, but the new wrapper scripts should be used instead for simplicity. There is now only a single \texttt{pythontex\_utils.py}, which works with both Python 2 and Python 3. % \item Added the \texttt{beta} package option. This makes the current version behave like v0.11beta, for compatibility. This option is temporary and will probably only be retained for a few releases. % \item Backward-incompatible changes (require the \texttt{beta} option to restore old behavior) % \begin{itemize} % \item The \texttt{pyverb} environment has been renamed \texttt{pyverbatim}. The old name was intended to be concise, but promoted confusion with LaTeX's \texttt{\string\verb} macro. % \item For \texttt{\string\printpythontex}, \texttt{\string\stdoutpythontex}, and \texttt{\string\stderrpythontex}, the modes \texttt{inlineverb} and \texttt{v} have been replaced by \texttt{verb}, and the old mode \texttt{verb} has been replaced by \texttt{verbatim}. This brings naming conventions in line with standard LaTeX \texttt{\string\verb} and \texttt{verbatim}, avoiding a source of potential confusion. % \item The \texttt{\string\setpythontexpyglexer}, \texttt{\string\setpythontexpygopt}, and \texttt{\string\setpygmentspygopt} commands now take an optional argument and a mandatory argument, rather than two mandatory arguments. This creates better uniformity among current and planned settings macros. % \item The \texttt{\string\setpythontexformatter} and \texttt{\string\setpygmentsformatter} commands have been replaced by the \texttt{\string\setpythontexprettyprinter} and \texttt{\string\setpygmentsprettyprinter} commands. This anticipates possible upcoming features. It also avoids potential confusion with Pygments's formatters and the utilities class's \texttt{formatter()} method. % \end{itemize} % \item Deprecated (still work, but raise warnings; after a few releases, they will raise errors instead, and after that eventually be removed) % \begin{itemize} % \item The \texttt{rerun} setting \texttt{all} was renamed \texttt{always}, in preparation for upcoming features. % \item The \texttt{stderr} option is replaced by \texttt{makestderr}. The \texttt{print}/\texttt{stdout} option is replaced by \texttt{debug}. These are intended to prevent confusion with future features. % \item The \texttt{fixlr} option is deprecated. It was originally introduced to deal with some of SymPy's LaTeX formatting, which has since changed. % \item The utilities class method \texttt{init\_sympy\_latex()} is deprecated. The \texttt{sympy\_latex()} and \texttt{set\_sympy\_latex()} methods now automatically initialize themselves on first use. % \end{itemize} % \item Added \texttt{autostdout} package option and \texttt{\string\setpythontexautostdout}, to complement \texttt{autoprint}. Added |prettyprinter| and |prettyprintinline| package options to complement new settings commands. % \item Added quickstart guide. % \item Installer now installs gallery and quickstart files, if present. % \end{changelog} % % \begin{changelog}{v0.11beta}{2013/02/17} % \item Commands like \texttt{\string\py} can now bring in any valid LaTeX code, including verbatim content, under the pdfTeX and XeTeX engines. Verbatim content was not allowed previously. LuaTeX cannot bring in verbatim, due to a known bug. % \item Added package option \texttt{depythontex} and scripts \texttt{depythontex*.py}. These allow a PythonTeX document to be converted into a pure LaTeX document, with no Python dependency. The package option creates an auxiliary file with extension \texttt{.depytx}. The \texttt{depythontex*.py} scripts take this auxiliary file and the original LaTeX document, and combine the two to produce a new document that does not rely on the PythonTeX package. All PythonTeX commands and environments are replaced by their output. All Python-generated content is substituted directly into the document. By default, all typeset code is wrapped in \texttt{\string\verb} and \texttt{verbatim}, but \texttt{depythontex*.py} has a \texttt{-{}-listing} option that allows \texttt{fancyvrb}, \texttt{listings}, \texttt{minted}, or \texttt{pythontex} to be used instead. % \item The current PythonTeX version is now saved in the \texttt{.pytxcode}. If this does not match the version of the PythonTeX scripts, a warning is issued. This makes it easier to determine errors due to version mismatches. % \item Fixed an incompatibility with the latest release of \texttt{xstring} (version 1.7, 2013/01/13). % \item Fixed a bug in the \texttt{console} environment that could cause problems when switching from Pygments highlighting to \texttt{fancyvrb} when using the \texttt{fvextfile} option. Fixed a bug introduced in the v0.10beta series that prevented the \texttt{console} environment from working with \texttt{fancyvrb}. % \item Fixed a bug with PythonTeX verbatim commands and environments that use Pygments. The verbatim commands and environments were incorrectly treated as if they had the attributes of executed code in the v0.10beta series. % \item Fixed a bug from the v0.10beta series that sometimes prevented imports from \texttt{\_\_future\_\_} from working when there were multiple sessions. % \item Fixed a bug related to hashing dependencies' mtime under Python 3. % \end{changelog} % % \begin{changelog}{v0.10beta2}{2013/01/23} % \item Improved \texttt{pythontex*.py}'s handling of the name of the file being processed. A warning is no longer raised if the name is given with an extension; extensions are now processed (stripped) automatically. The filename may now contain a path to the file, so you need not run \texttt{pythontex*.py} from within the document's directory. % \item Added command-line option \texttt{-{}-verbose} for more verbose output. Currently, this prints a list of all processes that are launched. % \item Fixed a bug that could crash \texttt{pythontex*.py} when the package option \texttt{pygments=false}. % \item Added documentation about \texttt{autoprint} behavior in the preamble. Summary: \texttt{code} commands and environments are allowed in the preamble as of v0.10beta. \texttt{autoprint} only applies to the body of the document, because nothing can be typeset in the preamble. Content printed in the preamble can be brought in by explicitly using \texttt{\string\printpythontex}, but this should be used with great care. % \item Revised \texttt{\string\stdoutpythontex} and \texttt{\string\printpythontex} so that they work in the preamble. Again, this should be used with great care if at all. % \item Revised treatment of any content that custom code attempts to print. Custom code is not allowed to print to the document (see documentation). If custom code attempts to print, a warning is raised, and the printed content is included in the \texttt{pythontex*.py} run summary. % \item One-line entries in stderr, such as those produced by Python's \texttt{warnings.warn()}, were not previously parsed because they are of the form \texttt{::} rather than \texttt{line~}. These are now parsed and synchronized with the document. They are also correctly parsed for inclusion in the document via \texttt{\string\stderrpythontex}. % \item If the package option \texttt{stderrfilename} is changed, all sessions that produced errors or warnings are now re-executed automatically, so that their stderr content is properly updated with the new filename. % \end{changelog} % % \begin{changelog}{v0.10beta}{2013/01/09} % \item Backward-incompatible: Redid treatment of command-line options for \texttt{pythontex*.py}, using Python's \texttt{argparse} module. Run \texttt{pythontex*.py} with option \texttt{-h} to see new command line options. % \item Deprecated: \texttt{\string\setpythontexcustomcode} is deprecated in favor of the \texttt{\string\pythontexcustomc} command and \texttt{pythontexcustomcode} environment. These allow entry of pure code, unlike \texttt{\string\setpythontexcustomcode}. These also allow custom code to be added to the beginning or end of a session, via an optional argument. Improved treatment of errors and warnings associated with custom code. % \item The summary of errors and warnings now correctly differentiates errors and warnings produced by user code, rather than treating all of them as errors. By default, \texttt{pythontex*.py} now returns an exit code of 1 if there were errors. % \item The PythonTeX utilities class now allows external file dependencies to be specified via \texttt{pytex.add\_dependencies()}, so that sessions are automatically re-executed when external dependencies are modified (modification is determined via either hash or mtime; this is governed by the new \texttt{hashdependencies} option). % \item The PythonTeX utilities class now allows created files to be specified via \texttt{pytex.add\_created()}, so that created files may be automatically cleaned up (deleted) when the code that created them is modified (for example, name change for a saved plot). % \item Added the following package options. % \begin{itemize} % \item \texttt{stdout} (or \texttt{print}): Allows input of stdout to be disabled. Useful for debugging. % \item \texttt{runall}: Executes everything. Useful when code depends on external data. % \item \texttt{rerun}: Determines when code is re-executed. Code may be set to always run (same as \texttt{runall} option), or only run when it is modified or when it produces errors or warnings. By default, code is always re-executed if there are errors or modifications, but not re-executed if there are warnings. % \item \texttt{hashdependencies}: Determines whether external dependencies (data, external code files highlighted with Pygments, etc.) are checked for modification via hashing or modification time. Modification time is default for performance reasons. % \end{itemize} % \item Added the following new command line options. The options that are equivalent to package options are overridden by the package options when present. % \begin{itemize} % \item \texttt{-{}-error-exit-code}: Determines whether an exit code of 1 is returned if there were errors. On by default, but can be turned off since it is undesirable when working with some editors. % \item \texttt{-{}-runall}: Equivalent to new package option. % \item \texttt{-{}-rerun}: Equivalent to new package option. % \item \texttt{-{}-hashdependencies}: Equivalent to new package option. % \end{itemize} % \item Modified the \texttt{fixlr} option, so that it only patches commands if they have not already been patched (avoids package conflicts). % \item Added \texttt{\string\setpythontexautoprint} command for toggling autoprint on/off within the body of the document. % \item Installer now attempts to create symlinks under OS X and Linux with TeX Live, and under OS X with MacPorts Tex Live. % \item Performed compatibility testing under lualatex and xelatex (previously, had only tested with pdflatex). Added documentation for using these TeX engines; at most, slightly different preambles are needed. Modified the PythonTeX gallery to support all three engines. % \item Code commands and environments may now be used in the preamble. This, combined with the new treatment of custom code, allows PythonTeX to be used in creating LaTeX packages. % \item Added documentation for using PythonTeX in LaTeX programming. % \item Fixed a bug that sometimes caused incorrect line numbers with \texttt{stderr} content. Improved processing of stderr. % \item Fixed a bug in automatic detection of pre-existing listings environment. % \item Improved the detection of imports from \texttt{\_\_future\_\_}. Detection should now be stricter, faster, and more accurate. % \end{changelog} % % \begin{changelog}{v0.9beta3}{2012/07/17} % \item Added Unicode support, which required the Python code to be split into one set for Python 2 and another set for Python 3. This will require any old installation to be completely removed, and a new installation created from scratch. % \item Refactoring of Python code. Documents should automatically re-execute all code after updating to the new version. Otherwise, you should delete the PythonTeX directory and run PythonTeX. % \item Improved installation script. % \item Added package options: pyfuture, stderr, upquote, pyglexer, pyginline. Renamed the pygextfile option to fvextfile. % \item Added custom code and workingdir commands. % \item Added the console environment and associated options. % \item Rewrote pythontex\_utils*.py, creating a new, context-aware interface to SymPy's LatexPrinter class. % \item Content brought in via macros no longer uses labels. Rather, long defs are used, which allows line breaks. % \item Pygments highlighting is now default for PythonTeX commands and environments % \end{changelog} % % \begin{changelog}{v0.9beta2}{2012/05/09} % \item Changed Python output extension to .stdout. % \end{changelog} % % \begin{changelog}{v0.9beta}{2012/04/27} % \item Initial public beta release. % \end{changelog} % % % \DoNotIndex{\newcommand,\newenvironment} % \DoNotIndex{\#,\$,\%,\&,\@,\\,\{,\},\^,\_,\~,\ } % \DoNotIndex{\@ne} % \DoNotIndex{\advance,\begingroup,\catcode,\closein} % \DoNotIndex{\closeout,\day,\def,\edef,\else,\empty,\endgroup} % \DoNotIndex{\begin,\end,\bgroup,\egroup} % % \providecommand*{\url}{\texttt} % \newcommand{\pytex}{Python\TeX} % \GetFileInfo{pythontex.dtx} % \title{The \textsf{pythontex} package} % \author{Geoffrey M.\ Poore \\ \url{gpoore@gmail.com} \\ \href{https://github.com/gpoore/pythontex}{\texttt{github.com/gpoore/pythontex}}} % \date{\fileversion~from \filedate} % % \maketitle % % \begin{abstract} % \pytex\ provides access to Python from within \LaTeX\ documents. It allows Python code entered within a \LaTeX\ document to be executed, and the results to be included within the original document. Python code and the figure or calculation it creates may be side by side. The package also makes possible macro definitions that mix Python and \LaTeX\ code. In addition, \pytex\ provides syntax highlighting for many programming languages via the Pygments syntax highlighter. % % \pytex\ is fast and user-friendly. Python code is only executed when it has been modified, or when user-specified criteria are met. When code is executed, sessions automatically run in parallel. If Python code produces errors, the error message line numbers are synchronized with the \LaTeX\ document line numbers, so that it is easy to find the error source. Dependencies may be specified so that code is automatically re-executed whenever its dependencies are modified. % % Because documents that use \pytex\ mix \LaTeX\ and Python code, they are less suitable than plain \LaTeX\ documents for journal submission, sharing, and conversion to other formats. \pytex\ includes a |depythontex| utility that creates a copy of a document in which all \pytex\ content is replaced by its output. % % While Python is the focus of \pytex, the package will add basic support for additional programming languages in the near future. % \end{abstract} % % % \section*{Warning} % \pytex\ makes possible some pretty amazing things. But that power brings with it a certain risk and responsibility. Compiling a document that uses \pytex\ involves executing Python code, and potentially other programs, on your computer. You should only compile \pytex\ documents from sources you trust. \pytex\ comes with NO WARRANTY.\footnote{All \LaTeX\ code is licensed under the \href{http://www.latex-project.org/lppl.txt}{\LaTeX\ Project Public License (LPPL)} and all Python code is licensed under the \href{http://www.opensource.org/licenses/BSD-3-Clause}{BSD 3-Clause License}.} The copyright holder and any additional authors will not be liable for any damages. % % % % \pagebreak % \tableofcontents % \pagebreak % % % \section{Introduction} % % This introduction provides background and objectives for the \pytex\ package. To jump right in and get started, you may wish to consult the |pythontex_quickstart| and |pythontex_gallery| documents, as well as Sections~\ref{sec:installing-and-running} and \ref{sec:usage}, below. % % \LaTeX\ can do a lot,\footnote{\TeX\ is a Turing-complete language.} but the programming required can sometimes be painful.\footnote{As I learned in creating this package.} Also, in spite of the many packages available for \LaTeX, the libraries and packages of a general-purpose programming language are lacking. For these reasons, there have been multiple attempts to allow other languages to be used within \LaTeX.\footnote{I am not including the various web and weave dialects in my discussion, since they typically involve a web or weave document from which the .tex source is generated, and thus offer less strong integration with \LaTeX. Two sophisticated examples of this approach are \href{http://www.stat.uni-muenchen.de/~leisch/Sweave/}{Sweave} and \href{http://yihui.name/knitr/}{knitr}, both of which combine \LaTeX\ with the R language for tasks such as dynamic report generation.} % \begin{itemize} % \item \href{http://www.ctan.org/tex-archive/macros/latex/contrib/perltex/}{Perl\TeX} allows the bodies of \LaTeX\ macros to be written in Perl. % \item \href{http://www.ctan.org/tex-archive/macros/latex/contrib/sagetex/}{Sage\TeX} allows code for the Sage mathematics software to be executed from within a \LaTeX\ document. % \item Martin R.\ Ehmsen's \href{http://www.ctan.org/pkg/python}{|python.sty|} provides a very basic method of executing Python code from within a \LaTeX\ document. % \item \href{http://elec.otago.ac.nz/w/index.php/SympyTeX}{Sympy\TeX} allows more sophisticated Python execution, and is largely based on a subset of Sage\TeX. % \item \href{http://www.luatex.org/}{Lua\TeX} extends the pdf\TeX\ engine to provide Lua as an embedded scripting language, and as a result yields tight, low-level Lua integration. % \end{itemize} % % \pytex\ attempts to fill a perceived gap in the current integrations of \LaTeX\ with an additional language. It has a number of objectives, only some of which have been met by previous packages. % \begin{description} % \item[Execution speed]\hfill\\ In the approaches mentioned above, all the non-\LaTeX\ code is executed at every compilation of the \LaTeX\ document (Perl\TeX, Lua\TeX, and |python.sty|), or all the non-\LaTeX\ code is executed every time it is modified (Sage\TeX\ and Sympy\TeX). However, many tasks such as plotting and data analysis take significant time to execute. We need a way to fine-tune code execution, so that independent blocks of slow code may be separated into their own sessions and are only executed when modified. If we are going to split code into multiple sessions, we might as well run these sessions in parallel, further increasing speed. A byproduct of this approach is that it now becomes much more feasible to include slower code, since we can still have fast compilations whenever the slow code isn't modified. % \item[Compiling without executing]\hfill\\ Even with all of these features to boost execution speed, there will be times when we have to run slow code. Thus, we need the execution of non-\LaTeX\ code to be separated from compiling the \LaTeX\ document. We need to be able to edit and compile a document containing unexecuted code. Unexecuted code should be invisible or be replaced by placeholders. Sage\TeX\ and Sympy\TeX\ have implemented such a separation of compiling and executing. In contrast, Lua\TeX\ and Perl\TeX\ execute all the code at each compilation---but that is appropriate given their goal of simplifying macro programming. % \item[Error messages]\hfill\\ Whenever code is saved from a \LaTeX\ document to an external file and then executed, the line numbers for any error messages will not correspond to the line numbering of the original \LaTeX\ document. At one extreme, |python.sty| doesn't attempt to deal with this issue, while at the other extreme, Sage\TeX\ uses an ingenous system of |Try|/|Except| statements on every chunk of code. We need a system that translates all error messages so that they correspond to the line numbering of the original \LaTeX\ document, with minimal overhead when there are no errors. % \item[Syntax highlighting]\hfill\\ Once we begin using non-\LaTeX\ code, sooner or later we will want to typeset some of it, which means we need syntax highlighting. A number of syntax highlighting packages currently exist for \LaTeX; perhaps the most popular are |listings| and |minted|. |listings| uses pure \LaTeX. It has not been updated since 2007, which makes it a less ideal solution in some circumstances. |minted| uses the Python-based syntax highlighter Pygments to perform highlighting. Pygments can provide superior syntax highlighting, but |minted| can be very slow because all code must be highlighted at each compilation and each instance of highlighting involves launching an external Python process. We need high-speed, user-friendly syntax highlighting via Pygments.\footnote{The author recently started maintaining the \texttt{minted} package. In the near future, \texttt{minted} will inherit \pytex's speed enhancements, and the two packages will become largely compatible so far as highlighting is concerned.} % \item[Printing]\hfill\\ It would be nice for the |print| statement/function,\footnote{In Python, |print| was a statement until Python 3, when it became a function. The function form is available via import from |\textunderscore\textunderscore future\textunderscore\textunderscore| in Python 2.6 and later.} or its equivalent, to automatically return its output within the \LaTeX\ document. For example, using |python.sty| it is possible to generate some text while in Python, open a file, save the text to it, close the file, and then |\input| the file after returning to \LaTeX. But it is much simpler to generate the text and |print| it, since the printed content is automatically included in the \LaTeX\ document. This was one of the things that |python.sty| really got right. % \item[Pure code]\hfill\\ \LaTeX\ has a number of special characters (|#| \texttt{\$} |%| |&| |~| |_| |^| |\| |{| |}|), which complicates the entry of code in a non-\LaTeX\ language since these same characters are common in many languages. Sage\TeX\ and Sympy\TeX\ delimit all inline code with curly braces (|{}|), but this approach fails in the (somewhat unlikely) event that code needs to contain an unmatched brace. More seriously, they do not allow the percent symbol |%| (modular arithmetic and string formatting in Sage and Python) to be used within inline code. Rather, a |\percent| macro must be used instead. This means that code must (sometimes) be entered as a hybrid between \LaTeX\ and the non-\LaTeX\ language. Lua\TeX\ is somewhat similar: ``The main thing about Lua code in a TeX document is this: the code is expanded by TeX before Lua gets to it. This means that all the Lua code, even the comments, must be valid TeX!''\footnote{\url{http://wiki.contextgarden.net/Programming_in_LuaTeX}} In the case of Lua\TeX, though, there is the \href{http://www.ctan.org/pkg/luacode}{\texttt{luacode}} package that allows for pure Lua. % % This language hybridization is not terribly difficult to work around in the Sage\TeX\ and Sympy\TeX\ cases, and is actually a Lua\TeX\ feature in many contexts. But if we are going to create a system for general-purpose access to a non-\LaTeX\ language, we need \textbf{all} valid code to work correctly in \textbf{all} contexts, with no hybridization of any sort required. We should be able to copy and paste valid code into a \LaTeX\ document, without having to worry about hybridizing it. Among other things, this means that inline code delimiters other than \LaTeX's default curly braces |{}| must be available. % \item[Hybrid code]\hfill\\ Although we need a system that allows input of pure non-\LaTeX\ code, it would also be convenient to allow hybrid code, or code in which \LaTeX\ macros may be present and are expanded before the code is executed. This allows \LaTeX\ data to be easily passed to the non-\LaTeX\ language, facilitating a tighter integration of the two languages and the use of the non-\LaTeX\ language in macro definitions. % \item[Math and science libraries]\hfill\\ The author decided to create \pytex\ after writing a physics dissertation using \LaTeX\ and realizing how frustrating it can be to switch back and forth between a \TeX\ editor and plotting software when fine-tuning figures. We need access to a non-\LaTeX\ language like Python, MATLAB, or Mathematica that provides strong support for data analysis and visualization. To maintain broad appeal, this language should primarily involve open-source tools, should have strong cross-platform support, and should also be suitable for general-purpose programming. % \item[Language-independent implementation]\hfill\\ It would be nice to have a system for executing non-\LaTeX\ code that depends very little on the language of the code. We should not expect to be able to escape all language dependence. But if the system is designed to be as general as possible, then it may be expanded in the future to support additional languages. % \end{description} % % Python was chosen as the language to fulfill these objectives for several reasons. % \begin{itemize} % \item It is open-source and has good cross-platform support. % \item It has a strong set of scientific, numeric, and visualization packages, including \href{http://numpy.scipy.org/}{NumPy}, \href{http://www.scipy.org/}{SciPy}, \href{http://matplotlib.sourceforge.net/}{matplotlib}, and \href{http://sympy.org}{SymPy}. Much of the initial motivation for \pytex\ was the ability to create publication-quality plots and perform complex mathematical calculations without having to leave the \TeX\ editor. % \item We need a language that is suitable for scripting. Lua is already available via Lua\TeX, and in any case lacks the math and science tools.\footnote{One could use \href{http://labix.org/lunatic-python}{Lunatic Python}, and some numeric packages for Lua are \href{http://numlua.luaforge.net/}{in development}.} Perl is already available via Perl\TeX, although Perl\TeX's emphasis on Perl for macro creation makes it rather unsuitable for scientific work using the \href{http://pdl.perl.org/}{Perl Data Language (PDL)} or for more general programming. Python is one logical choice for scripting. % \end{itemize} % % Now at this point there will almost certainly be some reader, sooner or later, who wants to object, ``But what about language \textit{X}!'' Well, yes, in some respects the choice to use Python did come down to personal preference. But you should give Python a try, if you haven't already. You may also wish to consider the many interfaces that are available between Python and other languages. If you still aren't satisfied, keep in mind \pytex's ``language-independent'' implementation! Although \pytex\ is written to support Python within \LaTeX, the implementation has been specially crafted so that other languages may be supported in the near future. % % % % \section{Installing and running} % \label{sec:installing-and-running} % % \subsection{Installing \pytex} % % \pytex\ requires a \TeX\ installation. \href{http://www.tug.org/texlive/}{\TeX\ Live} or \href{http://miktex.org/}{MiK\TeX} are preferred. \pytex\ requires the |Kpathsea| library, which is available in both of these distributions. The following \LaTeX\ packages, with their dependencies, are also required: |fancyvrb|, |etex|, |etoolbox|, |xstring|, |pgfopts|, |newfloat|, and |color| or |xcolor|. If you are creating and importing graphics using Python, you will also need |graphicx|. The \href{http://www.ctan.org/pkg/mdframed}{\texttt{mdframed}} package is recommended for enclosing typeset code in boxes with fancy borders and/or background colors; \href{http://www.ctan.org/pkg/tcolorbox}{\texttt{tcolorbox}} and \href{http://www.ctan.org/pkg/framed}{\texttt{framed}} are other alternatives. % % \pytex\ also requires a \href{http://www.python.org/}{Python} installation. Python 2.7 is recommended for the greatest compatibility with scientific tools, although many scientific packages are now compatible with Python 3. Python 3.2 and later will work as well. Earlier versions of Python 2 and 3 are not compatible, at least not without several modifications to the \pytex\ scripts. The Python package \href{http://pygments.org/}{Pygments} must be installed for syntax highlighting to function. \pytex\ has been tested with Pygments 1.4 and later, but the latest version is recommended. For scientific work, or to compile the |pythontex_gallery| file, the following are also recommended: \href{http://numpy.scipy.org/}{NumPy}, \href{http://www.scipy.org/}{SciPy}, \href{http://matplotlib.sourceforge.net/}{matplotlib}, and \href{http://sympy.org}{SymPy}. % % \pytex\ consists of the following files: % \begin{itemize} % \item Installer file |pythontex.ins| % \item Documented \LaTeX\ source file |pythontex.dtx|, from which |pythontex.pdf| and |pythontex.sty| are generated % \item Main script |pythontex.py|, which imports from |pythontex2.py| or |pythontex3.py|, based on the Python version % \item Language definitions |pythontex_types2.py| and |pythontex_types3.py| % \item Utilities class |pythontex_utils.py| % \item |depythontex.py|, which imports from |depythontex2.py| or |depythontex3.py|, based on the Python version; used to remove \pytex\ dependence % \item |README| (in rst style) % \item |pythontex_gallery.tex| and |pythontex_gallery.pdf| % \item |pythontex_quickstart.tex| and |pythontex_quickstart.pdf| % \item Optional installation script |pythontex_install_texlive.py| for \TeX\ Live % \item Optional batch file |pythontex.bat| for use in launching |pythontex.py| under Windows % \item Optional conversion script |pythontex_2to3.py| for converting \pytex\ code written for Python 2 into a form compatible with Python 3 % \end{itemize} % The style file |pythontex.sty| may be generated by running \LaTeX\ on |pythontex.ins|. The documentation you are reading may be generated by running \LaTeX\ on |pythontex.dtx|. Some code is provided in two forms, one for Python 2 and one for Python 3 (names ending in |2| and |3|). Whenever this is the case, a version-independent wrapper is supplied that automatically runs the correct code based on the Python version. For example, there are two main scripts, |pythontex2.py| and |pythontex3.py|, but you should actually run |pythontex.py|, which imports the correct code based on the Python version.\footnote{Unfortunately, it is not possible to provide full Unicode support for both Python 2 and 3 using a single script. Currently, all code is written for Python 2, and then the Python 3 version is automatically generated via the |pythontex\_2to3.py| script. This script comments out code that is only for Python 2, and un-comments code that is only for Python 3.} % % If you want the absolute latest version of \pytex, you should install it manually from \href{https://github.com/gpoore/pythontex}{github.com/gpoore/pythontex}. A Python installation script is provided for use with \TeX\ Live. It has been tested with Windows, Linux, and OS~X, but may need manual input or slight modifications depending on your system. The installation script performs the steps described below. Note that you may have to run the script with elevated privileges, and may need to run it using the user's PATH. For example, under Ubuntu Linux, you may need the following: % \begin{verbatim} % sudo env PATH=$PATH python pythontex_install_texlive.py % \end{verbatim} % % The \pytex\ files should be installed within the \TeX\ directory structure as follows. % \begin{itemize} % \item \meta{\TeX\ tree root}|/doc/latex/pythontex/| % \begin{itemize} % \item |pythontex.pdf| % \item |README| % \item |pythontex_quickstart.tex| % \item |pythontex_quickstart.pdf| % \item |pythontex_gallery.tex| % \item |pythontex_gallery.pdf| % \end{itemize} % \item \meta{\TeX\ tree root}|/scripts/pythontex/| % \begin{itemize} % \item |pythontex.py|, |pythontex2.py| and |pythontex3.py| % \item |pythontex_types2.py| and |pythontex_types3.py| % \item |pythontex_utils.py| % \item |depythontex.py|, |depythontex2.py| and |depythontex3.py| % \end{itemize} % \item \meta{\TeX\ tree root}|/source/latex/pythontex/| % \begin{itemize} % \item |pythontex.dtx| % \item |pythontex.ins| % \end{itemize} % \item \meta{\TeX\ tree root}|/tex/latex/pythontex/| % \begin{itemize} % \item |pythontex.sty| % \end{itemize} % \end{itemize} % After the files are installed, the system must be made aware of their existence. Run |mktexlsr| to do this. In order for |pythontex.py| and |depythontex.py| to be executable, a symlink (\TeX\ Live under Linux), launching wrapper (\TeX\ Live under Windows), or batch file (general Windows) should be created in the |bin/|\meta{system} directory. For \TeX\ Live under Windows, simply copy |bin/win32/runscript.exe| to |bin/win32/pythontex.exe| to create the wrapper.\footnote{See the output of |runscript -h| under Windows for additional details.} % % % \subsection{Compiling documents using \pytex} % % Compiling a document with \pytex\ involves three steps: running a \LaTeX-compatible \TeX\ engine, running |pythontex.py| (preferably via a symlink, wrapper, or batch file, as described above), and finally running the \TeX\ engine again. The first \TeX\ run saves code into an external file where \pytex\ can access it. The second \TeX\ run pulls the \pytex\ output back into the document. % % If you plan to use code that contains non-ASCII characters such as Unicode, you should make sure that your document is properly configured: % \begin{itemize} % \item Under pdfLaTeX, your documents need |\usepackage[T1]{fontenc}| and |\usepackage[utf8]{inputenc}|, or a similar configuration. % \item Under LuaLaTeX, your documents need |\usepackage{fontspec}|, or a similar configuration. % \item Under XeLaTeX, your documents need |\usepackage{fontspec}| as well as |\defaultfontfeatures{Ligatures=TeX}|, or a similar configuration. % \end{itemize} % For an example of a \pytex\ document that will correctly compile under all three engines, see the |pythontex_gallery.tex| source. % % If you use XeLaTeX, and your source code contains tabs, you \textbf{must} invoke XeLaTeX with the |-8bit| option so that tabs will be written to file as actual tab characters rather than as the character sequence |^^I|.\footnote{See \url{http://tex.stackexchange.com/questions/58732/how-to-output-a-tabulation-into-a-file} for more on tabs with XeTeX.} % % |pythontex.py| requires a single command-line argument: the name of the .tex file to process. The filename can be passed with or without an extension; the script really only needs the |\jobname|, so any extension is stripped off.\footnote{Thus, \pytex\ works happily with .tex, .ltx, .dtx, and any other extension.} The filename may include the path to the file; you do not have to be in the same directory as the file to run \pytex. If you are configuring your editor to run \pytex\ automatically via a shortcut, you may want to wrap the filename in double quotes |"| to allow for space characters.\footnote{Using spaces in the names of .tex files is apparently frowned upon. But if you configure things to handle spaces whenever it doesn't take much extra work, then that's one less thing that can go wrong.} For example, under Windows with \TeX\ Live and Python 2.7 we would create the wrapper |pythontex.exe|. Then we could run \pytex\ on a file \meta{file~name}.tex using the command |pythontex.exe "|\meta{file~name}|"|. % % |pythontex.py| accepts the following optional command-line arguments. Some of these options duplicate package-level options, so that settings may be configured either within the document or at the command line. In the event that the command-line and package options conflict, the package options always override the command-line options. For variations on these options that are acceptable, run |pythontex.py -h|. % \begin{itemize} % \item |--encoding=|\meta{encoding} This sets the file encoding. Any encoding supported by Python's \href{http://docs.python.org/library/codecs.html}{\texttt{codecs}} module may be used. If an encoding is not specified, \pytex\ uses UTF-8. Note that the encoding \textbf{must} be used consistently; the .tex source, the \pytex\ output, and any external code files that \pytex\ highlights should all use the same encoding. If support for characters beyond ASCII is required, then additional \LaTeX\ packages are required; see the discussion of \TeX\ engines above. % \item |--error-exit-code={true,false}| By default, |pythontex.py| returns an exit code of 1 if there were any errors, and an exit code of 0 otherwise. This may be useful when \pytex\ is used in a scripting or command-line context, since the presence of errors may be easily detected. It is also useful with some \TeX\ editors. For example, \href{http://www.tug.org/texworks/}{TeXworks} automatically hides the output of external programs unless there are errors. % % But in some contexts, returning a nonzero exit code can be redundant. For example, with the \href{http://winshell.de/}{WinShell} editor under Windows with TeX Live, the complete output of \pytex\ is always available in the ``Output'' view, so it is clear if errors have occurred. Having a nonzero exit code causes |runscript.exe| to return an additional, redundant error message in the ``Output'' view. In such situations, it may be desirable to disable the nonzero exit code. % \item |--runall=[{true,false}]| This causes \textbf{all} code to be executed, regardless of modification or |rerun| settings. It is useful when code has not been modified, but a dependency such as a library or external data has changed. Note that the \pytex\ utilities class also provides a mechanism for automatically re-executing code that depends on external files when those external files are modified. % % There is an equivalent |runall| package option. The command-line option |--rerun=always| is essentially equivalent. % \item |--rerun={modified,errors,warnings,always}| This sets the threshold for re-executing code. By default, \pytex\ will rerun code that has been modified or that produced errors on the last run. Sometimes, we may wish to have a more lenient setting (only rerun if modified) or a more stringent setting (rerun even for warnings, or just rerun everything). |modified| only executes code that has been modified (or that has modified dependencies). |errors| executes all modified code as well as all code that produced errors on the last run; this is the default. |warnings| executes all modified code, as well as all code that produced errors or warnings. |always| executes all code always and is essentially equivalent to |--runall|. % % There is an equivalent |rerun| package option. % \item |--hashdependencies=[{true,false}]| This determines whether dependencies (external files highlighted by Pygments, code dependencies specified via |pytex.add_dependencies()|, etc.) are considered to be modified based on their hash or modification time. By default, mtime is used, since it is faster. The package option |hashdependencies| is equivalent. % % \item |--verbose| This gives more verbose output, including a list of all processes that are launched. % \end{itemize} % % \pytex\ currently does not provide means to choose between multiple Python installations; it will use the default Python installation. Support for multiple installations is unlikely to be added, since a cross-platform solution would be required.\footnote{Python 3.3's \texttt{py} launcher for Windows may make this more feasible.} If you need to work with multiple installations, you may wish to modify |pythontex_types*.py| to create additional command and environment families that invoke different versions of Python, based on your system. % % \pytex\ attempts to check for a wide range of errors and return meaningful error messages. But due to the interaction of \LaTeX\ and Python code, some strange errors are possible. If you cannot make sense of errors when using \pytex, the simplest thing to try is deleting all files created by \pytex, then recompiling. By default, these files are stored in a directory called |pythontex-files-|\meta{jobname}, in the same directory as your .tex document. See Section \ref{sec:troubleshooting} for more details regarding troubleshooting. % % % \section{Usage} % \label{sec:usage} % % \subsection{Package options} % Package options may be set in the standard manner when the package is loaded: % \begin{quote} % |\usepackage|\oarg{options}|{pythontex}| % \end{quote} % % All options are described as follows. The option is listed, followed by its possible values. When a value is not required, \meta{none} is listed as a possible value. In this case, the value to which \meta{none} defaults is also given. Each option lists its default setting, if the option is not invoked when the package is loaded. % % Some options have a command-line equivalent. Package options override command-line options. % % All options related to printed content are provided in two forms for convenience: one based on the word |print| and one based on |stdout|. % % % \DescribeMacro{beta=\meta{none}/true/false default:false \meta{none}=true} % % This option provides compatibility with the beta releases from before the full v0.11 release, which introduced some changes in syntax and command names. This option should \textbf{only} be used with old \pytex\ documents that require it. % % You are encouraged to update old documents, since this compatility option will only be provided for a few releases. % % % \DescribeMacro{runall=\meta{none}/true/false default:false \meta{none}=true} % % This option causes all code to be executed, regardless of whether it has been modified. This option is primarily useful when code depends on external files, and needs to be re-executed when those external files are modified, even though the code itself may not have changed. Note that the \pytex\ utilities class also provides a mechanism for automatically re-executing code that depends on external files when those external files are modified. % % A command-line equivalent |--runall| exists for |pythontex.py|. The package option |rerun=always| is essentially equivelent. % % % \DescribeMacro{rerun=modified/errors/warnings/always default:errors} % % This option sets the threshold for re-executing code. By default, \pytex\ will rerun code that has been modified or that produced errors on the last run. Sometimes, we may wish to have a more lenient setting (only rerun if modified) or a more stringent setting (rerun even for warnings, or always rerun). |modified| only executes code that has been modified. |errors| executes all modified code as well as all code that produced errors on the last run; this is the default. |warnings| executes all modified code, as well as all code that produced errors or warnings. |always| executes all code regardless of its condition. % % A command-line equivalent |--rerun| exists for |pythontex.py|. % % % \DescribeMacro{hashdependencies=\meta{none}/true/false default:false \meta{none}=true} % % When external code files are highlighted with Pygments, or external dependencies are specified via the \pytex\ utilities class, they are checked for modification via their modification time (Python's |os.path.getmtime()|). Usually, this should be sufficient---and it offers superior performance, which is important if data sets are large enough that hashing takes a noticeable amount of time. However, occasionally hashing may be necessary or desirable, so this option is provided. % % A command-line equivalent |--hashdependencies| exists for |pythontex.py|. % % % \DescribeMacro{autoprint=\meta{none}/true/false default:true \meta{none}=true} % % \DescribeMacro{autostdout=\meta{none}/true/false default:true \meta{none}=true} % % Whenever a |print| command/statement is used, the printed content will automatically be included in the document, unless the code doing the printing is being typeset.\footnote{Note that |autoprint| only works within the body of the document. The |code| command and environment can be used in the preamble, but |autoprint| is disabled there. It is usually a not a good idea to print in the preamble, because nothing can be typeset; the only thing that could be validly printed is \LaTeX\ commands that do not typeset content, such as macro definitions. Thus, it is appropriate that printed content is only brought in while in the preamble if it is explicitly requested via |\string\printpythontex|. This approach is also helpful for writing packages using \pytex, since the author does not have to worry about any \LaTeX\ commands printed by the package either not being included (if |autoprint| is relied upon, but the user turns it off) or being included twice (if |\string\printpythontex| is used and |autoprint| is enabled). Printing should only be used in the preamble with great care.} In that case, the printed content must be included using the |\printpythontex| or |\stdoutpythontex| commands. % % Printed content is pulled in directly from the external file in which it is saved, and is interpreted by \LaTeX\ as \LaTeX\ code. If you wish to avoid this, you should print appropriate \LaTeX\ commands with your content to ensure that it is typeset as you desire. Alternatively, you may use |\printpythontex| or |\stdoutpythontex| to bring in printed content in verbatim form, using those commands' optional |verb| and |verbatim| options. % % The |autoprint| (|autostdout|) option sets autoprint behavior for the entire document. This may be overridden within the document using the |\setpythontexautoprint| command. % % \DescribeMacro{debug} % % This option aids in debugging invalid \LaTeX\ code that is brought in from Python. It disables the inclusion of printed content/content written to stdout. Since printed content should almost \textbf{always} be included, a warning is raised when this option is used. Not including printed content is useful when the printed content contains \LaTeX\ errors, and would cause document compilation to fail. When the document fails to compile, this can prevent modified Python code from being written to the code file, resulting in an inescapable loop unless printed content is disabled or the saved output is deleted. % % Note that since commands like |\py| involve printing, they are also disabled. % % % \DescribeMacro{makestderr=\meta{none}/true/false default:false \meta{none}=true} % % This option determines whether the stderr produced by scripts is available for input by \pytex, via the |\stderrpythontex| macro. This will not be needed in most situations. It is intended for typeseting incorrect code next to the errors that it produces. This option is not |true| by default, because additional processing is required to synchronize stderr with the document. % % \DescribeMacro{stderrfilename=full/session/genericfile/genericscript default:full} % % This option governs the file name that appears in |stderr|. Python errors begin with a line of the form % \begin{quote} % | File "", line | % \end{quote} % By default (option |full|), || is the actual name of the script that was executed. The name will be in the form \meta{family~name}|_|\meta{session}|_|\meta{group}|.|\meta{extension}. For example, an error produced by a |py| command or environment, in the session |mysession|, using the default group (that is, the default |\restartpythontexsession| treatment), would be reported in |py_mysession_default.py|. The |session| option replaces the full file name with the name of the session, |mysession.py| in this example. The |genericfile| and |genericscript| options replace the file name with || and |