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
CodePudding user response:
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}
"""