Skip to content

Instantly share code, notes, and snippets.

@puterleat
Created July 17, 2013 09:39
Show Gist options
  • Save puterleat/6019178 to your computer and use it in GitHub Desktop.
Save puterleat/6019178 to your computer and use it in GitHub Desktop.
A simple pre-processor (the name is a play on Stata and Sweave, but this is much less fancy than Sweave) which grabs chunks of stata code from a markup file (e.g. latex or markdown) and runs this code using the Stata binary.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Steve
A simple pre-processor (the name is a play on Stata and Sweave, but this is
much less fancy than Sweave) which grabs chunks of stata code from a markup file
(e.g. latex or markdown) and runs this code using the Stata binary.
Requirements
pyparsing
clint
sarge
pip install pyparsing clint sarge
Options
[--stata PATH] Path to the current stata binary. Default is /Applications/Stata/Stata.app/Contents/MacOS/Stata
--keep Do not delete temporary stata .do file.
License: http://opensource.org/licenses/BSD-2-Clause
"""
from pyparsing import *
import os
import sys
import time
import sarge
import clint
from clint import args
from clint.textui import puts, indent
data = args.files and "\n\n".join([open(i, 'r').read() for i in args.files]) or clint.piped_in()
if not data:
print "Nothing to process"
exit
DEFAULT_STATA = ["/Applications/Stata/Stata.app/Contents/MacOS/Stata"]
stata_binary = args.grouped.get('--stata', DEFAULT_STATA)[0]
ParserElement.setDefaultWhitespaceChars(" \t")
start = Suppress(CaselessLiteral("\\statacode"))
end = Suppress(CaselessLiteral("\\endstatacode")| CaselessLiteral("\\end"))
nl = CaselessLiteral("\r\n")
statacode = start + ZeroOrMore( ~end + (Word(printables)| LineEnd()) ) + end
stata_chunks = statacode.searchString(data)
stata_code = "\n".join([" ".join([i for i in j]) for j in stata_chunks])
stata_code = "cd {} \n {}".format(os.getcwd(), stata_code)
with open('_steve.do', 'w') as f:
f.write(stata_code + "\n")
r = sarge.run(stata_binary + " -e do _steve.do") #+ " ".join(stata_flags))
with open("steve.log", 'r') as f:
output = f.read()
output = output.replace(". \nend of do-file", "")
with open("steve.log", 'w') as f:
f.write(output)
if not getattr(args.flags, '--keep', None):
os.remove('_steve.do')
os.remove('steve.log')
if getattr(args.flags, '-v', None):
print output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment