pytex/pytex/pytex.py

101 lines
2.4 KiB
Python

#!/usr/bin/env python
# encoding: utf-8
"""
Feeding latex templates and compiling it
"""
import logging
import math as m
import subprocess
import random as rd
from path import Path
from .texenv import texenv
logger = logging.getLogger(__name__)
EXPORT_DICT = {}
EXPORT_DICT.update(m.__dict__)
EXPORT_DICT.update(rd.__dict__)
EXPORT_DICT.update(__builtins__)
def update_export_dict(new_dict):
"""Update global variable with new_dict
:param new_dict: needed tools across all template renders
"""
EXPORT_DICT.update(new_dict)
def feed(template, data, output, force=0):
""" Feed template with data to output
:param template: jinja2 template with textenv environment
:param data: Data dictionnary
:param output: name of the output file
"""
logger.info(f"Getting template {template}")
tpl = texenv.get_template(template)
output_p = Path(output)
output_dir = output_p.dirname()
if not output_dir.exists():
output_dir.mkdir()
if output_p.exists() and not force:
logger.error(f"{output} exists. Use force=1 do override it")
raise ValueError(f"{output} exists. Use force=1 do override it")
with open(output, "w") as output_f:
output_f.write(tpl.render(**EXPORT_DICT, **data))
logger.info(f"{template} has been rendered to {output}.")
def pdflatex(latex_file, output_dir=""):
""" Compile latex file
If output_dir is not set, it produce it next to the latex file.
"""
if not output_dir:
output_dir = Path(latex_file).dirname()
compilation = subprocess.Popen(
[
"pdflatex",
f"-output-directory={output_dir}",
latex_file,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
# shell=True
)
out, err = compilation.communicate()
if err:
logger.error(err)
if out:
logger.info(out)
logger.debug(f"{latex_file} has been compiled in {output_dir}")
def clean(dirname):
""" Clean the directory from aux and log latex files """
cleanning = subprocess.Popen(
[f"rm {dirname}/*.aux {dirname}/*.log"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
out, err = cleanning.communicate()
logger.error(err)
logger.info(out)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del