Search code examples
pythonerror-handlinglatexsweaveos.system

Detect and handle a LaTeX warning/error generated via an os.system call in Python


I wrote a python script to automate turning Sweave/LaTeX documents into PDFs. Here's the most important part:

os.system("""echo "Sweave('%s.Rnw')" | R --vanilla --quiet"""%topic)

seq = ['p','b','p','b','p','p']
for op in seq: 
    if op is 'p':
        os.system('pdflatex %s'%topic)
    if op is 'b':
        os.system('bibtex %s'%topic)
    if op is 'l':
        os.system('latex %s'%topic)

This works great if there are no errors, but if there is a LaTeX error, I am brought to the CLI for LaTeX e.g.,

[10]
! You can't use `macro parameter character #' in vertical mode.
l.625 #

? 

I then need to break out of this manually. Is there a way that I can let Python "know" that the os.system call generated an error in LaTeX and then end this call but still capturing the error text?


Solution

    1. Don't use os.system, use subprocess module instead.
    2. pdflatex has an -interaction switch that you can use to put it a non-interactive mode (you probably want batchmode or nonstopmode IIRC, but you can experiment and see what each option do).