Skip to content

Instantly share code, notes, and snippets.

@terryoy
Last active June 11, 2019 20:50
Show Gist options
  • Save terryoy/8066614 to your computer and use it in GitHub Desktop.
Save terryoy/8066614 to your computer and use it in GitHub Desktop.
Python example to show usage of command line arguments, configurations, and exceptions
[helloworld]
name = Terry
#!/usr/bin/python
from ConfigParser import ConfigParser, NoOptionError
import traceback
config = ConfigParser()
config.read('config.ini')
print 'an existing item value:', '[ name =', config.get('helloworld', 'name'), ']'
try:
print 'an non-existing item value:', '[ non-exist =', config.get('helloworld', 'non-exist'), ']'
except NoOptionError:
# pass
traceback.print_exc()
#!/usr/bin/python
import sys, getopt
def print_usage():
print 'main.py -i <input_file> -o <output_file>'
def main(argv):
inputfile = ''
outputfile = ''
try:
# opts is a list of returning key-value pairs, args is the options left after striped
# the short options 'hi:o:', if an option requires an input, it should be followed by a ":"
# the long options 'ifile=' is an option that requires an input, followed by a "="
opts, args = getopt.getopt(argv, 'hi:o:', ['ifile=', 'ofile='])
except getopt.GetoptError:
print_usage()
sys.exit(2)
# print(args) # debug line
if not opts:
print_usage()
sys.exit(2)
# print arguments
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit(2)
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print "Input file:", inputfile
print "Output file:", 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