#!/usr/bin/env python
-import sys, os, re, logging
+import sys, os, re
# Languages mapping as used by markdown/pandoc
shortname2language = dict(
tex='Tex',
)
-def read(text, argv=sys.argv[2:]):
+def read(text, argv=sys.argv[3:]):
lines = text.splitlines()
# First read all include statements
for i in range(len(lines)):
include_text = f.read()
lines[i] = include_text
text = '\n'.join(lines)
- logging.info('******* text after include:\n{}'.format(text))
# Run Mako
mako_kwargs = {}
lookup = TemplateLookup(directories=[os.curdir])
# text = text.encode('utf-8')
temp = Template(text=text, lookup=lookup, strict_undefined=True)
- logging.info('******* mako_kwargs: {}'.format(str(mako_kwargs)))
text = temp.render(**mako_kwargs)
- logging.info('******* text after mako:\n{}'.format(text))
-
# Parse the cells
lines = text.splitlines()
cells = []
if shortname:
# Check if code is to be typeset as static
# Markdown code (e.g., shortname=py-t)
- logging.info('******* found shortname {}'
- .format(shortname))
astext = shortname[-2:] == '-t'
- logging.info('******* cell: astext={} shortname={}'
- .format(astext, shortname))
if astext:
# Markdown
shortname = shortname[:-2]
inside = 'codecell'
cells.append(['codecell', fullname, []])
else:
- logging.info('******* cell: markdown')
# Markdown cell
inside = 'markdown'
cells.append(['markdown', 'text', ['\n']])
# Add an ending ``` of code
cells[i][2].append('```\n')
cells[i][2] = '\n'.join(cells[i][2])
- # TODO: optional logging
- import pprint
- logging.info('******* cell data structure:\b%s' % pprint.pformat(cells))
return cells
def write(cells):
def driver():
"""Compile a document and its variables."""
try:
- filename = sys.argv[1]
- with open(filename, 'r') as f:
+ inputfile = sys.argv[1]
+ with open(inputfile, 'r') as f:
text = f.read()
+ # Assuming file extension .gj (generate Jupyter); TODO: less strict
+ outputfile = inputfile[:-3]+'.ipynb' if (len(sys.argv)<=2 or sys.argv[2]=='-') \
+ else sys.argv[2]
except (IndexError, IOError) as e:
- print('Usage: %s filename' % (sys.argv[0]))
+ print('Usage: %s inputfile [outputfile|- [Mako args]]' % (sys.argv[0]))
print(e)
sys.exit(1)
- cells = read(text, argv=sys.argv[2:])
+ cells = read(text, argv=sys.argv[3:])
filestr = write(cells)
- # Assuming file extension .gj (generate Jupyter); TODO: less strict
- filename = filename[:-3] + '.ipynb'
- with open(filename, 'w') as f:
+ with open(outputfile, 'w') as f:
f.write(filestr)
if __name__ == '__main__':
- logfile = 'tmp.log'
- if os.path.isfile(logfile):
- os.remove(logfile)
- logging.basicConfig(format='%(message)s', level=logging.DEBUG,
- filename=logfile)
driver()