-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomm_rm.py
More file actions
61 lines (56 loc) · 2.45 KB
/
comm_rm.py
File metadata and controls
61 lines (56 loc) · 2.45 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
import sys
def remove_comments(source):
inside_string = False
inside_block_comment = False
string_char = None
block_comment_char = None
new_source = []
for line in source:
new_line = ''
i = 0
while i < len(line):
if not inside_string and line[i:i+3] in ['"""', "'''"]: # Check for block comment start or end
if inside_block_comment and block_comment_char == line[i:i+3]:
inside_block_comment = False
elif not inside_block_comment:
inside_block_comment = True
block_comment_char = line[i:i+3]
i += 3
elif not inside_block_comment and line[i] in ['"', "'"]: # Check for string start
# Toggle inside_string and copy the string literal
inside_string = not inside_string
string_char = line[i]
start = i
i += 1
# Handle string literal
while i < len(line) and (line[i] != string_char or (i < len(line) - 1 and line[i:i+2] == string_char*2)):
i += 1
i += len(string_char)
new_line += line[start:i]
elif not inside_string and not inside_block_comment and line[i] == '#': # Comment detected outside of a string
break # Ignore the rest of the line
else:
new_line += line[i] # Copy other characters
i += 1
if new_line.strip() and not inside_block_comment: # Check if the line is not empty and not inside a block comment
new_source.append(new_line) # Add the line to the new source
return new_source
def main():
if len(sys.argv) != 2:
print("Usage: python comm_rm.py input_file.py")
sys.exit(1)
input_filename = sys.argv[1]
output_filename = input_filename.replace('.py', '_rm.py')
try:
with open(input_filename, 'r') as file:
source_code = file.readlines()
new_source = remove_comments(source_code)
with open(output_filename, 'w') as file:
file.writelines(new_source) # Write lines without stripping newline characters
print(f"Comments removed. Clean file saved as: {output_filename}")
except FileNotFoundError:
print(f"File {input_filename} not found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
main()