Skip to content

Instantly share code, notes, and snippets.

@pckujawa
Created March 30, 2012 03:06
Show Gist options
  • Save pckujawa/2246120 to your computer and use it in GitHub Desktop.
Save pckujawa/2246120 to your computer and use it in GitHub Desktop.
parsing inputs from commandline and creating a latex file from python
from optparse import OptionParser
import os
import re
import subprocess
import sys
parser = OptionParser(usage=__doc__.strip())
parser.add_option('-v', dest='verbose', action='store_true',
help='Verbose output')
header_pat = re.compile(r'^\\PY\{c\}\{' + (r'\\PYZsh\{\}' * 8))
def yield_altered_lines(latex):
"""
Adds page breaks and page layout to our pygments file. Blah.
"""
for line in latex.splitlines():
if line == r'\documentclass{article}':
yield line
yield r'\usepackage{geometry}'
yield r'\geometry{letterpaper,landscape,margin=0.25in}'
elif line == r'\begin{document}':
yield line
yield r'\large'
elif header_pat.search(line):
yield r'\end{Verbatim}'
yield r'\pagebreak'
yield r'\begin{Verbatim}[commandchars=\\\{\}]'
yield line
else:
yield line
if __name__ == '__main__':
print
options, args = parser.parse_args()
if options.verbose:
errout = sys.stderr
else:
errout = open('/tmp/pep20.log', 'w')
try:
# TODO: pygmentize in Python instead of farming it out
p = subprocess.Popen(
('pygmentize', '-f', 'latex', '-l', 'python',
'-O', 'full', sys.argv[0]),
stdout=subprocess.PIPE, stderr=errout)
output, err = p.communicate()
assert p.returncode == 0, 'pygmentize exited with %d' % p.returncode
p2 = subprocess.Popen(
('pygmentize', '-f', 'html', '-l', 'python',
'-O', 'full', '-o', 'pep20_by_example.html', sys.argv[0]),
stdout=errout, stderr=errout)
p2.communicate()
assert p2.returncode == 0, 'pygmentize exited with %d' % p2.returncode
except OSError, e:
print >> sys.stderr, 'Failed to run pygmentize: %s' % str(e)
except AssertionError, e:
print e
altered_output = '\n'.join(l for l in yield_altered_lines(output))
try:
p = subprocess.Popen(('pdflatex',),
stdin=subprocess.PIPE, stdout=errout, stderr=errout)
p.communicate(altered_output)
assert p.returncode == 0, 'pdflatex exited with %d' % p.returncode
except OSError, e:
print >> sys.stderr, 'Failed to run pygmentize: %s' % str(e)
except AssertionError, e:
print e
os.rename('texput.pdf', 'pep20_by_example.pdf')
errout.close()
@pckujawa
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment