Is there any way to convert a .py script file (on Python) to LaTeX code?
Not sure if I get what you're asking for.
You can use the inputminted
command of the minted
package to generate a PDF file (not a .tex) from a Python script.
For example, if your main LaTeX file is:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{minted}
\begin{document}
\inputminted{python}{script.py}
\end{document}
and your script.py
file is:
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
you can get the following PDF:
Update
Just read your comment to Teepeemm.
You can convert your .py
file into a .ipynb
using something like p2j, and then into .tex
using the nbconvert
function of jupyter
.
Related videos on Youtube
Dani
Updated on December 19, 2020Comments
-
Dani almost 3 years
In the same way you can convert a jupyter notebook file to
.tex
file by usingnbconvert
package, I was wondering if there exist an equivalent way to do the same stuff but with.py
script file as input.The behavior would be like:
Program takes a
.py
file as input.Program returns a
.tex
file as output (with its highlights, indents, colors, etc).
-
Teepeemm almost 4 yearsThe listings package can include Python (and other languages) in the pdf output. I'm not quite sure what you mean by outputting a .tex file with highlights, indents, colors, etc. TeX files are pure text, which doesn't have those things.
-
Dani almost 4 yearsI mean that the .tex output file should include the necessary latex commands in order to replicate the whole format of .py file. can listings package deal with it?
-
Dani almost 4 yearsThanks, but i get the following output error when compiling (on TexStudio) --> Package minted Error: You must invoke LaTeX with the -shell-escape flag. Do you know what is this?
-
NVaughan almost 4 yearsDon't know. I'm using Linux and the terminal directly. You need to have
pygmentize
installed. Perhaps thelisting
package, suggested by Teepeemm, can do the same without it. -
Dani almost 4 yearsOk I will search for information, ;)
-
Tomáš Kruliš almost 4 yearsSure that is right. --shell-escape alleviates some restrictions on TeX and allows it to use scripts in your PATH environment variable. I dont know TeXstudio; In TeXworks, there is a list of compilation-tools, and -shell-escape is one of command line arguments for compilation.