Validate CLI Port Inputs: Parse integer, Check range, Reject before work

Validate a Python CLI Port Number with an Argparse Type Converter

Reject invalid port arguments before your Python script starts work, using a small argparse converter with clear errors and boundary tests.

A Python command-line option declared with type=int rejects words, but it still accepts integers outside your application’s permitted range. If your tool requires an explicitly selected, nonzero port, validate both conversion and range with a custom argparse type function. This catches a typo before the script attempts a connection or begins other work.

The example below accepts integers from 1 through 65535. That is an application rule, not a claim that every accepted value is available or appropriate. Some socket APIs give port zero a special automatic-allocation meaning; this particular interface deliberately does not offer that behaviour.

Keep the validation function small and predictable

Save this complete example as port_check.py. It parses an argument and prints the accepted value. It does not open a socket, scan another machine, change a firewall or start a service.

import argparse


def port_number(text):
    try:
        value = int(text)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("port must be an integer") from exc
    if not 1 <= value <= 65535:
        raise argparse.ArgumentTypeError("port must be between 1 and 65535")
    return value


def main():
    parser = argparse.ArgumentParser(description="Validate a nonzero port number")
    parser.add_argument("--port", required=True, type=port_number)
    args = parser.parse_args()
    print(f"Validated port: {args.port}")


if __name__ == "__main__":
    main()

The converter receives the argument text, converts it once, checks the result and returns an integer. Raising ArgumentTypeError lets argparse produce its normal usage message and argument-specific explanation. There is no need to print an error and then continue with a substitute value.

Try valid values and boundary failures

Run each command separately in your terminal. Use python3 as shown on systems where that launches Python; on Windows, substitute your installed Python launcher, such as py.

python3 port_check.py --port 8443
python3 port_check.py --port 1
python3 port_check.py --port 65535
python3 port_check.py --port 0
python3 port_check.py --port 65536
python3 port_check.py --port abc
python3 port_check.py --port 3.5
python3 port_check.py

The first three commands should print the validated number and finish successfully. Zero and 65536 should report the range error; words and a decimal string should report the integer error. Omitting the required option should produce argparse’s missing-argument error. Invalid command lines terminate with status 2 rather than reaching the final print statement.

These are expected behaviours for this example, not evidence that a real network operation succeeded. A script wrapper should preserve a failed child command’s status rather than assuming that any completed process succeeded.

Do not confuse conversion with environment checks

An accepted integer is only a syntactically suitable input under this application’s rule. It does not prove that a server is listening, the chosen port is unused, the operating system permits binding, or the user has permission to contact a destination. Perform the relevant operational checks later and handle their errors separately.

Python’s integer conversion also accepts some representations beyond bare ASCII digits, including surrounding whitespace and a leading plus sign. If your interface requires a stricter textual format, specify that requirement and add a separate format check. Do not describe this converter as enforcing a digits-only wire format.

Avoid validation that has side effects

Do not put a connection attempt, file creation or long-running service discovery inside this converter. Parsing should remain cheap and understandable, especially when a later argument might still be rejected. The official documentation recommends simple conversions here and more involved resource management after argument parsing.

Likewise, do not catch every exception and convert it to a generic bad-port message. That can hide a programming defect. This function handles the expected integer-conversion failure and its own explicit range rule.

Review checklist and common questions

  • Are both endpoints of the permitted range tested?
  • Are the adjacent invalid values rejected?
  • Does a missing option stop execution?
  • Does downstream code receive an integer, not the original string?
  • Are network permissions and runtime failures handled outside parsing?

Can I use choices instead? Argparse supports choices, including numeric choices, but a converter provides a short, purpose-specific error without presenting a large range as a list of allowed values.

Does this disable abbreviated options? No. That is a separate parser setting. See disabling argparse long-option abbreviations if operational scripts should require complete option names.

Source and safe use

Reference: Python’s argparse documentation, particularly type conversion, supported converter exceptions and invalid arguments.

This tutorial is for educational purposes. Test carefully before production use. The site owner is not responsible for misuse, damage, data loss or production issues.

Leave a Reply

Your email address will not be published. Required fields are marked *