Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import os, sys, argparse, tempfile, shutil, subprocess
- parser = argparse.ArgumentParser(description='Convert LaTeX equation to png image')
- parser.add_argument('equation', help='LaTeX equation to convert')
- parser.add_argument('--confirm', help='Don\'t ask about outputting to terminal')
- args = parser.parse_args()
- if sys.stdout.isatty() and not args.confirm:
- response = input('Are you sure you want to output binary PNG data to the terminal? [y/N] ')
- if not (response and response[0] in 'yY'):
- sys.exit()
- dvipng_args = ['-T', 'tight', '-bg', 'transparent']
- for program in ('latex', 'dvipng'):
- if not shutil.which(program):
- sys.exit('Error: {0} not installed'.format(program))
- cwd = os.getcwd()
- with tempfile.TemporaryDirectory() as tempdir:
- os.chdir(tempdir)
- try:
- with open('file.tex', 'w') as latexfile:
- latexfile.write(
- "\\nonstopmode\\documentclass[12pt]{article}\n"
- "\\usepackage{amsmath}\n"
- "\\usepackage{amssymb}\n"
- "\\usepackage{cancel}\n"
- "\\pagestyle{empty}\n"
- "\\begin{document}\n$$\n"
- + args.equation +
- "\n$$\n\\end{document}\n"
- )
- latexprocess = subprocess.run(
- ['latex', 'file.tex', '-output-directory', tempdir],
- stdout=subprocess.DEVNULL)
- if latexprocess.returncode != 0:
- print('Error running latex', file=sys.stderr)
- sys.exit()
- dvipngprocess = subprocess.run(
- ['dvipng', 'file.dvi'] + dvipng_args,
- stdout=subprocess.DEVNULL)
- if dvipngprocess.returncode != 0:
- print('Error running dvipng', file=sys.stderr)
- subprocess.run(['zsh'])
- sys.exit()
- with open('file1.png', 'rb') as pngfile:
- shutil.copyfileobj(pngfile, sys.stdout.buffer)
- finally:
- os.chdir(cwd)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement