-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathextract_tutorial_code.py
More file actions
70 lines (53 loc) · 1.94 KB
/
extract_tutorial_code.py
File metadata and controls
70 lines (53 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Extract tutorial python code into a executable python scripts."""
import re
import sys
if len(sys.argv) >= 2:
tutorials_rst = sys.argv[1:]
else:
raise ValueError(
"Must provide at least one .rst file contaiing code examples"
)
for tutorial_rst in tutorials_rst:
tutorial = []
code_block = False
caption = False
with open(tutorial_rst, mode="r") as f:
for line in f.readlines():
line = line.strip()
code = re.split("^\s*>>>\s", line)
if len(code) == 2:
if re.findall("# Raises Exception\s*$", line):
code[1] = (
"try:\n "
+ code[1]
+ "\nexcept Exception:\n pass"
)
else:
code = re.split("^\s*\.\.\.\s", line)
if len(code) == 2:
tutorial.append(code[1])
continue
if re.match("\s*\.\. Code Block Start", line):
code_block = True
tutorial.append("# Start of code block")
continue
if code_block:
if re.match("\s*\.\. code-block::", line):
continue
if not caption and re.match("\s*:caption:", line):
caption = True
continue
if caption:
# Blank line marks end of caption
if re.match("\s*$", line):
caption = False
continue
if re.match("\.\. Code Block End", line):
code_block = False
tutorial.append("# End of code block")
continue
tutorial.append(line.replace(" ", "", 1))
tutorial.append("")
tutorial_py = tutorial_rst.replace(".rst", ".py")
with open(tutorial_py, "w") as f:
f.write("\n".join(tutorial))