Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I insert values into my python generated latex?

I have a following problem. I need to generate latex using python. I try:

import subprocess


content = """\documentclass{article}
\begin{document}
\thispagestyle{empty}
\hfill  \textbf{\huge Invoice number. 2022-00%(faktura_n)s} \hfill   \\
\end{document}
"""


def main():
    with open('cover.tex','w') as f:
        content = f.read()
        page = content % {'faktura_n' : '27'}
        f.write(page)

    subprocess.call(["pdflatex", "cover.tex"])

if __name__ == "__main__":
    main()

but I got an error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 71, in <module>
  File "<input>", line 63, in main
io.UnsupportedOperation: not readable

How can I insert faktura_n into the content, please? I found this, but it did not help me: Generating pdf-latex with python script

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just remove the line content = f.read() (see my comment) and double the backslashes in your string:

import subprocess

content = """\\documentclass{article}
\\begin{document}
\\thispagestyle{empty}
\\hfill  \\textbf{\\huge Invoice number. 2022-00%(faktura_n)s} \\hfill   \\\\
\\end{document}
"""

def main():
    with open('cover.tex','w') as f:
        page = content % {'faktura_n' : '27'}
        f.write(page)
    subprocess.call(["pdflatex", "cover.tex"])

if __name__ == "__main__":
    main()

or better (credit to @JiříBaum), use an r-string (raw string) to avoid doubling backslashes:

content = r"""\documentclass{article}
\begin{document}
\thispagestyle{empty}
\hfill  \textbf{\huge Invoice number. 2022-00%(faktura_n)s} \hfill   \\
\end{document}
"""
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading