0
In my previous post on Argparse I had some issues with validating values and printing help output for values that are out of range. I got some great suggestions from my smart colleagues Mikkel Troest and Patrick Ogenstad who are far more advanced in their Python knowledge.
We started out with the following code in the last post:
#!/usr/bin/env python
# import Argparse
import argparse
# import sys
import sys
# create main function
def main():
# create ArgumentParser object
parser = argparse.ArgumentParser(description="Daniel's ping script v0.1")
# add arguments
parser.add_argument("-version", "--version", action="version", version="%(prog)s 0.1")
parser.add_argument("-c", "--c" , help="Number of packets", action="store", type=int, choices=xrange(1, 1000), metavar=("(1-1000)"))
parser.add_argument("-s", "--s" , help="packetsize in bytes", action="store", type=int, choices=xrange(56, 1500), metavar=("(56-1500)"))
parser.add_argument("-t", "--t" , help="ttl for icmp packets", action="store", type=int, choices=xrange(1, 255), metavar=("(1-255)"))
parser.add_argument("-w", "--w" , help="timeout in seconds", action="store", type=int, choices=xrange(1, 10), metavar=("(1-10)"))
parser.add_argument("-ip", "--ip", help="ip address", action="store", required=True)
# parse command-line arguments
parser.parse_args()
if __name__ == "__main__" and len(sys.argv) < 2:
print "use the -h flag for help on this script"
else:
main()
First let’s clean up this a bit since the length of the lines are more than 80 characters Continue reading