Skip to content

Instantly share code, notes, and snippets.

@amackcrane
Last active March 9, 2020 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amackcrane/9e932706e57974cbd6ee601d3db57dbd to your computer and use it in GitHub Desktop.
Save amackcrane/9e932706e57974cbd6ee601d3db57dbd to your computer and use it in GitHub Desktop.
knitr::spin functionality for python
#!/bin/bash
## Rmarkdown has an engine for native python code, but
## knitr::spin (which facilitates dual report/script
## functionality without code duplication by translating
## from .R to .Rmd) doesn't.
## Luckily, we don't need to parse anything, just convert
## markdown annotations to plain text, and code chunks to
## rmarkdown format.
## Note that, unlike with knitr::spin, code not in chunks
## (i.e. following a markdown line) is currently ignored.
# take in .py file as $1
# make new filename from $1
fname=${1%.py}.Rmd
# setup outfile
rm -f $fname
touch $fname
echo "$fname"
uninit=true
chunk=
# slurp file
while IFS= read -r line;
do
# if we're currently in a code chunk
if [ $chunk ]
then
# and hit either MD or a new chunk...
if [[ $line =~ ^\#[\+\'] ]]
then
# finish code chunk
printf '```\n' >> $fname
chunk=""
else
# otherwise leave code be
echo "$line" >> $fname
fi
fi
# markdown line
if [[ $line =~ ^\#\' ]]
then
# strip pound jawn
echo "$line" | sed "s|#' *||" >> $fname
# code chunk beginning
elif [[ $line =~ ^\#\+ ]]
then
# if this is the first chunk
if [ $uninit ]
then
# slide in there and do some opts_chunk$set
printf '\n```{r autosetup, echo=FALSE}\nknitr::opts_chunk$set(echo=FALSE, results="hide")\n```\n' \
>> $fname
uninit=
fi
# reformat to rmd python chunk
# going to great lengths to prepend a newline
echo "$line" | sed -E 's|#\+ *(.*)|```{python \1}|' | \
xargs -0 printf "\n%s" >> $fname
chunk=true
fi
done <$1
# If we ended the file in a code chunk, we'll know
if [ $chunk ]
then
# in case file didn't end in newline
echo "$line" >> $fname
printf '```\n' >> $fname
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment