几点说明:
例如:
import argparse
import ipaddress
# Assuming this is about an IP address and a port.
CONN_HELP = "Connection string must have the format IP_ADDRESS:PORT."
def valid_conn_str(conn):
"""Validate the connection string passed as a positional argument"""
# If the colon is missing, the connection string is malformatted.
if ":" not in conn:
raise argparse.ArgumentTypeError(CONN_HELP)
parts = conn.split(":")
# If there are two or more colons,
# the connection string is malformatted.
if len(parts) > 2:
raise argparse.ArgumentTypeError(CONN_HELP)
# If the port part of the connection string is not an integer,
# the connection string is malformatted.
try:
port = int(parts[1])
except ValueError:
raise argparse.ArgumentTypeError(CONN_HELP + " PORT must be an integer.")
# If the port number is larger than 65535,
# the connection string is malformatted
if port > 65535:
raise argparse.ArgumentTypeError(CONN_HELP + " PORT must be < 65535.")
# You could add similar checks in order to validate the IP address
# or whatever else you are expecting as the first part of the
# connection string.
#
# If it is indeed an IP address, you could use the
# ipaddress module for that, e.g.:
try:
ip_addr = ipaddress.ip_address(parts[0])
except ValueError:
raise argparse.ArgumentTypeError(CONN_HELP + " Invalid IP address.")
# When all checks have passed, return the values.
return parts[0], port
parser = argparse.ArgumentParser()
parser.add_argument(
"conn",
metavar="CONN_STRING",
# Use the validator function to check the format.
type=valid_conn_str,
help=CONN_HELP,
)
# args contains all arguments that have been passed in.
args = parser.parse_args()
# The validation function returns two values,
# therefore connection string argument is a tuple.
target = args.conn[0]
port = args.conn[1]
print(target)
print(port)
当有人现在调用脚本时,例如:
$ my_script.py hello:world
他们会看到
usage: my_script.py [-h] CONN_STRING
my_script.py: error: argument CONN_STRING: Connection string must have the format IP_ADDRESS:PORT. PORT must be an integer.
使用有效的端口但无效的 IP 地址运行它
$ my_script.py hello:123
将给予:
usage: my_script.py [-h] CONN_STRING
my_script.py: error: argument CONN_STRING: Connection string must have the format IP_ADDRESS:PORT. Invalid IP address.
使用有效的 IP 地址和端口运行
$ my_script.py 123.123.123:123
将打印
123.123.123.123
123