4

I have the following python source code:

def modulo(a, n):
    return a % n

print(modulo(3, 10))
print(modulo(10, 10))
print(modulo(11, 10))

The first function definition gives a hint about the implementation and the calls below show exemplary usage / output.

I want to typeset this the following way (so people can copy&paste the implementation and see some live output):

def modulo(a, n):
    return a % n

>>> print(modulo(3, 10))
3
>>> print(modulo(10, 10))
0
>>> print(modulo(11, 10))
1

I failed to create this using PythonTeX.

\begin{pyblock}[mysession][]
def modulo(a, n):
    return a % n

\end{pyblock}

\begin{pyconsole}[mysession][]
print(modulo(3, 10))
print(modulo(10, 10))
print(modulo(11, 10))

\end{pyconsole}

This gives me

def modulo(a, n):
    return a % n

>>> print(modulo(3, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined
>>> print(modulo(10, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined
>>> print(modulo(11, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined

The documentation mentions sessions, where code is run in parallel so I put those code snippets explicitly into the same session (even though per default both are run in default).

I definitely need a PythonTeX solution. Any ideas?

5

Console code and normal code each have their own separate default sessions. All commands/environments starting with pycon execute completely separately from those beginning with py. There is no overlap between them.

A feature to do what you want has been requested and will be implemented in an upcoming release of PythonTeX. In the meantime, you can probably do what you want with this workaround, copied from that feature request.

\documentclass{article}

\usepackage{pythontex}

\newenvironment{pyconcodeblock}%
 {\VerbatimEnvironment
  \begin{VerbatimOut}{temp.py}}%
 {\end{VerbatimOut}%
  \pyconc{exec(compile(open('temp.py', 'rb').read(), 'temp.py', 'exec'))}%
  \inputpygments{python}{temp.py}}

\begin{document}

\begin{pyconcodeblock}
def foo(x):
    return 2*x
\end{pyconcodeblock}

\begin{pyconsole}
x = 10
foo(x)
\end{pyconsole}

\end{document}
  • Perfect answer resolving my session confusion and providing a workaround. The workaround does not work for me. Either the file temp.py does not exist or an AttributeError is raised. But this will be discussed on github. Thanks! – meisterluk Apr 27 '15 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.