Skip to content

Instantly share code, notes, and snippets.

@plammens
Last active June 25, 2019 17:55
Show Gist options
  • Save plammens/472535730c5b7acb4c78b74ee74f2fe5 to your computer and use it in GitHub Desktop.
Save plammens/472535730c5b7acb4c78b74ee74f2fe5 to your computer and use it in GitHub Desktop.
Python script to gather all of the code in an `RMarkdown` file's code chunks and print it to stdout
import re
import argparse
START_PATT = re.compile(r'^```\{r([ \w]*).*\}$')
END_PATT = re.compile(r'^```$')
HEADER_PATT = re.compile(r'^(?P<level>#+) (?P<name>.+)$')
def get_chunk(file) -> str:
def lines():
for line in file:
if re.match(END_PATT, line):
return
yield line
return ''.join(lines())
def get_code(file) -> str:
def chunks():
for line in file:
header_match = re.match(HEADER_PATT, line)
if header_match:
name = header_match.group('name')
level = len(header_match.group('level'))
side = '-'*(5*(5 - level))
sep = '\n'*(4 if level <= 2 else 2)
yield sep
yield f'# {side} {name if level > 2 else name.upper()} {side}\n'
chunk_match = re.match(START_PATT, line)
if chunk_match:
yield '\n'
yield get_chunk(file)
return ''.join(chunks())
def file_type(filename: str):
return open(filename, 'r')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', type=file_type)
args = parser.parse_args()
code = get_code(args.file)
print(code)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment