Last active
December 11, 2017 23:18
-
-
Save eubnara/a976b8d66d4ca527668b86b795c80c57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import re | |
import sys | |
if 2 != len(sys.argv): | |
print "Usage: %s <filename>" % sys.argv[0] | |
exit(1) | |
want_to_set = {'net.ipv4.ip_forward': '1'} | |
# get currently set variables | |
def get_custom_variables(filename): | |
custom_var = {} | |
f = open(filename) | |
while True: | |
line = f.readline() | |
if not line: | |
break | |
line = line.strip() | |
if re.match('^# eub', line) or re.match('^#.*', line): | |
continue | |
splitted = line.split('=') | |
if 2 == len(splitted): | |
(key, value) = [i.strip() for i in splitted] | |
custom_var[key] = value | |
f.close() | |
return custom_var | |
# add currently set variables | |
for key, value in get_custom_variables(sys.argv[1]).iteritems(): | |
if key in want_to_set: | |
continue | |
else: | |
want_to_set[key] = value | |
f = open(sys.argv[1]) | |
while True: | |
line = f.readline() | |
if not line: | |
break | |
line = line.strip() | |
# when there is a newline only | |
if 0 == len(line): | |
continue | |
if re.match('^# eub', line): | |
break | |
# do not modify comments | |
if re.match('^#.*', line): | |
print line | |
else: | |
splitted = line.split('=') | |
if 2 == len(splitted): | |
key = splitted[0].strip() | |
if key in want_to_set: | |
print "#%s" % line | |
else: | |
print line | |
f.close() | |
print "# eub" | |
for k, v in want_to_set.iteritems(): | |
print "%s=%s" % (k, v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The reason why I don't read a file reversely is that the "# eub" comment(delimiter) may not exist.