1

I am writing out some parameters to JSON files using pythontex, but would like to add context information in form of section numbers (for example \thesection or \thesubsubsection, perhaps also the page number or other counters).

Is there a straightforward way to pass the values of the section counters to Python?

  • Josef
Josef
  • 13

1 Answers1

1

There are different ways this could be done. Here's one approach. For another approach, see \setpythontexcontext in the pythontex documentation.

The pythontex commands like \pyc are designed to send code verbatim to Python. The trick here is to fully expand \thesection before storing it in a Python variable.

\documentclass{article}
\usepackage{pythontex}
\makeatletter
\newcommand{\sectopy}{%
  \edef\sectopy@val{\thesection}%
  \expandafter\sectopy@i\expandafter{\sectopy@val}}
\def\sectopy@i#1{\pyc{section = #1}}
\makeatother

\begin{document}

\section{Section}

\sectopy

The section is: \py{section}

\end{document} 
G. Poore
  • 12,417
  • I don't see how \setpythontexcontext can be used for this purpose, since \setpythontexcontext can only be used in the preamble. – Josef Mar 01 '19 at 16:56
  • 1
    @Josef \setpythontexcontext is used in the preamble to define a set of contextual data that is always available and up to date. So if you defined it to contain section=\thesection, then within Python code pytex.context.section would always contain the current section number. – G. Poore Mar 01 '19 at 17:23