-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathremove_runnable_code.py
More file actions
58 lines (51 loc) · 2.43 KB
/
remove_runnable_code.py
File metadata and controls
58 lines (51 loc) · 2.43 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
import sys
STATE_IN_MULTILINE_COMMENT_BLOCK_DOUBLE_QUOTE = "STATE_IN_MULTILINE_COMMENT_BLOCK_DOUBLE_QUOTE"
STATE_IN_MULTILINE_COMMENT_BLOCK_SINGLE_QUOTE = "STATE_IN_MULTILINE_COMMENT_BLOCK_SINGLE_QUOTE"
STATE_NORMAL = "STATE_NORMAL"
def remove_runnable_code(python_file_path, output_file_path):
with open(python_file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
ret_lines = []
state = STATE_NORMAL
for line in lines:
if state == STATE_NORMAL:
if line.startswith('#'):
ret_lines.append(line)
state = STATE_NORMAL
elif ((line.startswith('"""') or line.startswith('r"""')) and
line.endswith('"""')):
ret_lines.append(line)
state = STATE_NORMAL
elif line.startswith('"""') or line.startswith('r"""'):
ret_lines.append(line)
state = STATE_IN_MULTILINE_COMMENT_BLOCK_DOUBLE_QUOTE
elif ((line.startswith("'''") or line.startswith("r'''")) and
line.endswith("'''")):
ret_lines.append(line)
state = STATE_NORMAL
elif line.startswith("'''") or line.startswith("r'''"):
ret_lines.append(line)
state = STATE_IN_MULTILINE_COMMENT_BLOCK_SINGLE_QUOTE
else:
ret_lines.append("\n")
state = STATE_NORMAL
elif state == STATE_IN_MULTILINE_COMMENT_BLOCK_DOUBLE_QUOTE:
if line.startswith('"""'):
ret_lines.append(line)
state = STATE_NORMAL
else:
ret_lines.append(line)
state = STATE_IN_MULTILINE_COMMENT_BLOCK_DOUBLE_QUOTE
elif state == STATE_IN_MULTILINE_COMMENT_BLOCK_SINGLE_QUOTE:
if line.startswith("'''"):
ret_lines.append(line)
state = STATE_NORMAL
else:
ret_lines.append(line)
state = STATE_IN_MULTILINE_COMMENT_BLOCK_SINGLE_QUOTE
ret_lines.append("\n# %%%%%%RUNNABLE_CODE_REMOVED%%%%%%")
with open(output_file_path, 'w', encoding='utf-8') as file:
for line in ret_lines:
file.write(line)
if __name__ == "__main__":
remove_runnable_code(sys.argv[1], sys.argv[2])