PythonTeX

PythonTeX は,LaTeX ドキュメントの中に埋め込んだ Python コードを実行して,その結果を元の場所に出力するためのパッケージです. Python 以外に Bash, JavaScript, Julia, Octave, Perl, R, Raku, Ruby, Rust, SageMath もサポートしています.



インストール

TeX Live に含まれています.

PythonTeX の利用には,パッケージ自体の他に Python のインタプリタと Pygments という Python モジュールが必要になります. Pygments は pip を使ってインストールできます.

pip3 install pygments

でインストールできます.

使い方

例として,次を pow.tex として保存してみましょう.

\documentclass{article}
\usepackage{pythontex}
\newcommand{\pow}[2]{\py{#1**#2}}
\begin{document}
$2^{10}=\pow{2}{10}$.
\end{document}

これを pdflatex で処理します(platex でも大丈夫です).

$ pdflatex pow
...
No file pythontex-files-pow/pow.pytxmcr.
Run PythonTeX to create it.
Package PythonTeX Warning: Missing autoprint content on input line 5.
...

このようなログが出て,pow.pytxcode という中間ファイルが生成されます. これを pythontex で処理すれば,Python コードの実行結果が含まれた pythontex-files-pow/pow.pytxmcr というファイルが生成されます. さらにもう一度 pdflatex を実行すれば,2の10乗の値が正しく埋め込まれます.

$ pythontex pow
This is PythonTeX 0.14

--------------------------------------------------
PythonTeX:  pow - 0 error(s), 0 warning(s)

$ pdflatex pow
...

まとめると,PythonTeX では latex → pythontex → latex の順でコマンドを実行する必要があります.

注意点

pythontex を実行したときに

Traceback (most recent call last):
  File "c:/w32tex/share/texmf-dist/scripts/pythontex/pythontex.py", line 55, in
<module>
    import pythontex3 as pythontex
  File "c:\w32tex\share\texmf-dist\scripts\pythontex\pythontex3.py", line 61, in
 <module>
    from pygments.styles import get_all_styles
ImportError: No module named 'pygments'

のように ImportError: No module named 'pygments' のエラーが発生する場合は pygments がインストールされていません.インストールを参照して下さい.

関連リンク


Last-modified: 2022-11-12 (土) 16:41:59 (524d)