Skip to content

Instantly share code, notes, and snippets.

@chrislawlor
Created January 12, 2016 23:33
Show Gist options
  • Save chrislawlor/f12149436fb5ecc9aaf0 to your computer and use it in GitHub Desktop.
Save chrislawlor/f12149436fb5ecc9aaf0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Removes commented lines from an input list of lines.
Commented lines are defined simply as lines that begin with "#" or ";"
Example usage:
uncomment config.ini
- or -
cat config.ini | uncomment
Yes, I know you can do this with awk or grep or whatever, but a simple
'uncomment' is easy to remember and suits me.
"""
import sys
COMMENT_TOKENS = "#;"
def is_a_comment(line):
line = line.strip()
try:
first_char = line[0]
return first_char in COMMENT_TOKENS
except IndexError:
# Don't think we should be getting blank lines here, but just in case
return False
def uncommented_lines(lines):
for line in lines:
if line.strip() and not is_a_comment(line):
yield line
def process_lines(input_stream):
for line in uncommented_lines(input_stream):
sys.stdout.write(line)
if __name__ == "__main__":
if not sys.stdin.isatty():
input_stream = sys.stdin
process_lines(sys.stdin)
sys.exit(0)
else:
try:
input_filename = sys.argv[1]
except IndexError:
message = "Need filename as a first argument, or use a pipe\n"
sys.stderr.write(message)
sys.exit(1)
with open(input_filename, "r") as input_file:
process_lines(input_file)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment