Skip to content

Instantly share code, notes, and snippets.

@yzh119
Created November 12, 2018 04:29
Show Gist options
  • Save yzh119/04fd7760fb0509f19d22916289273656 to your computer and use it in GitHub Desktop.
Save yzh119/04fd7760fb0509f19d22916289273656 to your computer and use it in GitHub Desktop.
Conver RST file to sphinx-gallery `.py` format
"""
Usage:
python convert.py xxx.rst xxx.py
To convert markdown to sphinx_gallery `.py`, use pandoc to generate a `.rst` text in advance:
pandoc xxx.md --output xxx.rst
python convert.py xxx.rst xxx.py
"""
import sys
input_filename = sys.argv[1]
output_filename = sys.argv[2]
with open(input_filename, 'r') as f_in:
with open(output_filename, 'w') as f_out:
inside_python = False
for line in f_in:
if not inside_python and line.startswith('.. code:: python='):
inside_python = True
continue
if inside_python:
if line.startswith(' '):
f_out.write(line[4:])
continue
elif line.startswith('\t'):
f_out.write(line[1:])
continue
elif len(line) > 1:
inside_python = False
f_out.write('##############################################################################\n')
else:
f_out.write('\n')
continue
if len(line) > 1:
f_out.write('# ' + line)
else:
f_out.write('#\n')
@Divyosmi
Copy link

Nice code.

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