Skip to content

Instantly share code, notes, and snippets.

@phobson
Created October 13, 2015 01:19
Show Gist options
  • Save phobson/5026de44e53f9b3b0dec to your computer and use it in GitHub Desktop.
Save phobson/5026de44e53f9b3b0dec to your computer and use it in GitHub Desktop.
context manager for compile latex documents
import subprocess
import glob
import os
class LaTeXDirectory(object):
""" Context manager to help compile latex docs from python.
Switches to the latex document's folder and remains there while
inside the manager. The present working directory is restored once
the context manager exits.
Parameters
----------
texpath : string
The LaTeX source file or the directory in which it is found.
"""
def __init__(self, texpath):
self.home = os.getcwd()
if os.path.isfile(texpath):
self.texpath = os.path.dirname(texpath)
else:
self.texpath = texpath
def __enter__(self):
os.chdir(self.texpath)
return self
def __exit__(self, *args):
os.chdir(self.home)
def compile(self, texdoc, clean=False):
# use ``pdflatex`` to compile the document
tex = subprocess.call(['pdflatex', texdoc, '--quiet'], shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if clean:
extensions = ['aux', 'log', 'nav', 'out', 'snm', 'toc']
for ext in extensions:
junkfiles = glob.glob('*.{}'.format(ext))
for junk in junkfiles:
os.remove(junk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment