2 ms·
Do I add more to this code just for convention? The command line option parsing (or broken ParseOptions dependency) will become magnitudes larger and more comp
by mmphosis 6y ago
Do I add more to this code just for convention? The command line option parsing (or broken ParseOptions dependency) will become magnitudes larger and more complex than what the program does.
usage = 0
argc = len(sys.argv)
if argc == 2 and sys.argv[1] == "-r":
hex2bin()
else:
if argc == 2 and sys.argv[1].startswith('-w', 0, 2):
s = sys.argv[1][2::]
elif argc == 3 and sys.argv[1] == '-w':
s = sys.argv[2]
elif argc >= 2:
usage = 1
if usage == 0:
try:
width = int(s)
except ValueError:
print("Error: invalid, -w {}".format(s))
usage = 1
except NameError:
width = 40
if usage == 0:
bin2hex(width)
else:
print("usage: mondump [-r | -w width]")
print(" Convert binary to hex or do the reverse.")
print(" -r reverse operation: convert hex to binary.")
print(" -w maximum width: fit lines within width (default is 40.)")
sys.exit(usage)
- tom_ 6y agoNo, you take code away by using argparse! Handles all this GNU longopt and argument parsing stuff for you, and autogenerates the --help display. Probably something like this: import argparse def auto_int(x): return int(x,0) # http://stackoverflow.com/questions/25513043/ def main(argv): parser=argparse.ArgumentParser() parser.add_option('-r',dest='reverse',action='store_true',help='reverse operation: convert hex to binary') parser.add_option('-w',default=40,dest='width',nargs='?',type=auto_int,help='maximum width: fit lines within width (default is %(default)s.)") options=parser.parse_args(sys.argv[1:]) if options.reverse: bin2hex(options.width) else: hex2bin() if __name__=='__main__': main(sys.argv[1:])