2

How can I access a float variable defined via \pgfmathsetmacro from pythontex?

Something like:

\documentclass{article}

\usepackage[gobble=auto]{pythontex}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \pgfmathsetmacro{\a}{1.7}
  \begin{pycode}
  a = \getvar{\a}
  \end{pycode}
\end{tikzpicture}


\end{document}
Skillmon
  • 60,462
student
  • 29,003

2 Answers2

3

One way to do this would be to define a new command for assigning Python variables. The example below will expand a macro once and is meant for numbers. Working with strings would require a slightly different approach to insert quotation marks and provide any necessary character escaping.

\documentclass{article}

\usepackage{pythontex}
\usepackage{tikz}

\makeatletter
\newcommand{\pythontexassign}[2]{%
  \expandafter\pythontexassign@i\expandafter{#2}{#1}}
\newcommand{\pythontexassign@i}[2]{%
  \pyc{#2=#1}}
\makeatother

\begin{document}

\begin{tikzpicture}
\pgfmathsetmacro{\myvar}{1.7}
\pythontexassign{myvar}{\myvar}
\end{tikzpicture}

\begin{pycode}
print(myvar)
\end{pycode}

\end{document}
G. Poore
  • 12,417
2

\setpythontexcontext is made for this kind of stuff I think, but it can only be used in the preamble. It takes a comma-separated list of key-value arguments that will be turned into a dictionary named pytex.context.

(Note also that \a is already used, see Short names for macros, so it might not be a good name for a macro.)

\documentclass{article}
\usepackage{pythontex}
\usepackage{tikz}
\pgfmathsetmacro{\MyVarA}{1.7}
\setpythontexcontext{a=\MyVarA}
\begin{document}

%\begin{tikzpicture}

\begin{pycode}
a = pytex.context['a']
print(a)
\end{pycode}
%\end{tikzpicture}
\end{document}
Torbjørn T.
  • 206,688