Last active
August 29, 2015 13:58
-
-
Save thelahunginjeet/9957047 to your computer and use it in GitHub Desktop.
basic example of python parsing of command-line arguments
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/python | |
import sys, getopt | |
def config_file_parser(configfile): | |
""" | |
Very basic code for reading a simple config file and returning | |
a dictionary of options. | |
""" | |
config = {} | |
with open(configfile,'r') as f: | |
for line in f: | |
# assumes a rigid format : name=value | |
atoms = [x.strip() for x in line.strip().split('=')] | |
config[atoms[0]] = int(atoms[1]) | |
f.close() | |
return config | |
def write_output(config, outputfile): | |
""" | |
Just dumps the values of the config dict to the output file | |
specified; assumes all config values are ints. | |
""" | |
f = open(outputfile,'w') | |
# does not print them in a controlled order! | |
f.write('%s\n' % ','.join([str(x) for x in config.values()])) | |
f.close() | |
def main(argv): | |
# parse the options and set the filenames | |
configfile='' | |
outputfile='' | |
try: | |
opts,args = getopt.getopt(argv,"c:o:",["config=","output="]) | |
except getopt.GetoptError: | |
print 'myscript.py -c <configfile> -o <outputfile>' | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt in ("-c","--config"): | |
configfile = arg | |
elif opt in ("-o","--output"): | |
outputfile = arg | |
# read the config file | |
config = config_file_parser(configfile) | |
# now do a dump to output | |
write_output(config,outputfile) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment