Is it possible to differentiate between arguments based on a regex with argparse?
I would like my script to accept either an IP address or a network address, but need to be able to differentiate between the two because the backend API call requires me to specify which is used. I'd preferably not use an explicit flag to specify which argument is used, instead using a regex, but not sure this is possible?
Example usage:
ip-lookup.py 192.168.1.1
192.168.1.1 should be assigned to an argument named 'ip'
ip-lookup.py 192.168.0.0/16
ip-lookup.py 192.168.0.0 255.255.0.0
ip-lookup.py 192.168.0.0/255.255.0.0
192.168.0.0/16 should be assigned to an argument named 'network'
Code:
parser = argparse.ArgumentParser(description='Lookup an IP address or network in the backend IPAM system.')
parser.add_argument('ip', help='IP host address', type=str, required=False, **regex to match on IP address**)
parser.add_argument('network', help='IP network address', type=str, required=False, **regex to match on IP network**)
args = parser.parse_args()
args.ip -> should only exist if the user entered an IP address as parameter
args.network -> should only exist if the user entered an IP network as parameter
network? Why is there a space hereip-lookup.py 192.168.0.0 255.255.0.0?[argparse]question attempts something similar - stackoverflow.com/questions/53944971/….positionalarguments are assigned strictly on position. It does not do 'value' matching. That's something you can do after parsing with your own code.required=Falsewill raise an error.