Created
December 1, 2016 08:09
-
-
Save ellieayla/39f77840f5cc4d6b8d59dd2fa93627f1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
from __future__ import print_function | |
import sys | |
from configparser import RawConfigParser, NoOptionError | |
from itertools import chain | |
import argparse | |
def strip_quotes(s): | |
DOUBLE='"' | |
SINGLE="'" | |
if s.startswith(SINGLE) and s.endswith(SINGLE): | |
s = s.strip(SINGLE) | |
elif s.startswith(DOUBLE) and s.endswith(DOUBLE): | |
s = s.strip(DOUBLE) | |
return s | |
if __name__=="__main__": | |
parser = argparse.ArgumentParser(description='Modify a VMX file, retrieving, setting or clearing parameters.', | |
epilog="Example:\n5fup0e.py 5fup0e.vmx --set serial0.present=TRUE --set serial0.startConnected=TRUE --set serial0.fileType=file --set serial0.fileName=/tmp/outputfile") | |
parser.add_argument("filename", type=str, help="Path to .vmx file") | |
parser.add_argument("-s", "--set", action='append', default=[], metavar='KEY=VALUE', help="Set KEY to VALUE. If it doens't exist, add it.") | |
parser.add_argument("-g", "--get", action='append', default=[], metavar='KEY', help="Retrieve value of existing KEY") | |
parser.add_argument("-G", "--getall", action='store_true', help="Retrieve all existing values") | |
parser.add_argument("-c", "--clear", action='append', default=[], metavar='KEY', help="Remove existing KEY") | |
args = parser.parse_args() | |
config = RawConfigParser() | |
config.optionxform = str | |
with open(args.filename) as lines: | |
lines = chain(("[default]\n",), lines) | |
config.read_file(lines) | |
for key in args.get: | |
try: | |
print("{0} = {1}".format(key, strip_quotes(config.get('default', key)))) | |
except NoOptionError as e: | |
pass # ignore missing options | |
if args.getall: | |
for (key, value) in config.items('default'): | |
print("{0} = {1}".format(key, value)) | |
for key in args.clear: | |
config.remove_option('default', key) | |
if args.set or args.clear: | |
for param in args.set: | |
(key, value) = param.split("=", 1) | |
config.set('default', key.strip(), "{0}".format(value.strip())) | |
with open(args.filename, "w") as fp: | |
for (key, value) in config.items('default'): | |
fp.write('{0} = {1}\n'.format(key, value)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment