Executing python script or code using \input not working

inputpdftexpython

Im trying to execute a python script from within LaTeX by means of using the \input command, however I get a strange error that I can't really understand. Im following the working example taken from this answer but it simply won't work.

Example 1: \input{|python3 -c 'print(1+2)'} gives the error ! LaTeX Error: File `|python3 -c 'print(1+2)'.tex' not found.
Note there's a tilde there after just before the |

Example 2: \input{|python3 test.py} gives the error ! LaTeX Error: File `|python3 test.py' not found.

Note again there's a tilde there after just before the |

Im currently using PDFLaTeX with the –shell-escape flag, but I can't really make it work.

What am I doing wrong? Here is the full code:

\documentclass[10pt, export]{standalone}
\usepackage{tikz}
\usepackage{animate}
\usepackage{amsmath}
\usepackage[left=0cm, top=0cm, bottom=-2cm, right=0cm, paperwidth=12in, paperheight=6.75in]{geometry}
\usepackage{circuitikz}

\begin{document}

\input{|python3 -c 'print(1+2)'}
\input{|python3 test.py}

\end{document}

Best regards and thanks in advance

UPDATE:

Trying David's answer produces this output:

! LaTeX Error: File `|python3 -c 'print(1+2)'.tex' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: tex)

Enter file name: 
! Emergency stop.
<read *> 
         
l.10 1+2 = \input{|python3 -c 'print(1+2)'}
                                           ^^M
!  ==> Fatal error occurred, no output PDF file produced!

These are the flags I'm using with PDFLatex under Kile:

--shell-escape -synctex=1 -interaction=nonstopmode %source

The same is output when compiled from the terminal as follows:

pdflatex --shell-escape -interaction=nonstopmode test.tex

Best Answer

It works if you use TeX's primitive \input, which is saved in LaTeX as \@@input:

This is script.py:

print("Number four: %d." % 4)

This works:

\documentclass{article}

\makeatletter  % to use \@@input
\def\runshell#1{%
    \@@input"|#1"\relax
}
\makeatother


\begin{document}
a\runshell{python3 -c 'print(1+2)'}b

a\runshell{python3 script.py}b

\end{document}

enter image description here

Related Question