Skip to content

Python API

Everything below is importable from the top-level clijson package unless noted otherwise.

Parsing

parse

parse(
    output: str | bytes,
    command: str | None = None,
    platform: str | Platform | None = None,
    *,
    normalize: bool = False,
    engines: Sequence[str] | None = None,
    strict: bool = False,
    raise_on_error: bool = False,
) -> ParseResult

Parse the output of a show/display command into JSON-ready data.

Parameters:

Name Type Description Default
output str | bytes

raw text captured from the device (prompts, pagers and ANSI codes are tolerated and removed)

required
command str | None

the command that produced the output; abbreviations are fine (sh ip int br). If omitted, it is read from the prompt line echoed at the top of output when present.

None
platform str | Platform | None

"iosxr", "junos", "vrp" or any alias. If omitted it is auto-detected from the prompt, the command verb and output fingerprints.

None
normalize bool

also compute a vendor-neutral view in result.normalized for commands that map to a common model (interfaces, BGP neighbors, routes, LLDP, ...).

False
engines Sequence[str] | None

engines to try, in order. Default: ("native", "ntc", "genie", "generic"); unavailable optional engines are skipped silently.

None
strict bool

only accept a dedicated parser; raise :class:ParserNotFound otherwise.

False
raise_on_error bool

re-raise exceptions from dedicated parsers instead of falling back to the next engine.

False

parse_file

parse_file(
    path: PathLike,
    command: str | None = None,
    platform: str | Platform | None = None,
    **kwargs: Any,
) -> ParseResult | list[ParseResult]

Parse a file. Session logs with several prompts yield a list of results.

parse_session

parse_session(
    text: str,
    platform: str | Platform | None = None,
    **kwargs: Any,
) -> list[ParseResult]

Parse every command found in a terminal session capture.

split_session

split_session(text: str) -> list[SessionChunk]

Split a captured terminal session into (command, output) chunks.

Works with logs containing many commands (e.g. a PuTTY/SecureCRT log or a script capture) as long as prompts are visible.

Results

ParseResult dataclass

ParseResult(
    data: Any,
    platform: str | None,
    command: str | None,
    engine: str,
    parser: str | None = None,
    confidence: float = 1.0,
    intent: str | None = None,
    params: dict[str, str] = dict(),
    warnings: list[str] = list(),
    normalized: Any = None,
    metadata: dict[str, Any] = dict(),
    raw: str | None = None,
)

Structured output plus provenance.

data is the parsed output. Everything else explains how it was obtained so that automation can decide how much to trust it:

  • engine - native (dedicated parser), xml/json (the device emitted structured data), config (configuration tree), ntc/genie/ttp (optional third-party engines) or generic (heuristic fallback that works on any output).
  • confidence - 0..1, 1.0 for native parsers.

to_dict

to_dict(meta: bool = True) -> Any

Data plus provenance; with meta=False just the (normalized, if available) data.

records

records() -> list[dict[str, Any]]

The most table-like view of the result as a list of flat dicts.

Uses the normalized view when available, otherwise the largest list of records found in data (a dict keyed by name becomes rows with a name column).

to_dataframe

to_dataframe() -> Any

records() as a pandas DataFrame (requires pandas).

to_json

to_json(
    indent: int | None = 2,
    meta: bool = False,
    **kwargs: Any,
) -> str

JSON string. meta=True wraps the data with provenance fields.

Comparing captures

diff

diff(
    before: ParseResult | Any,
    after: ParseResult | Any,
    ignore: str | Pattern[str] | None = VOLATILE,
    normalized: bool = True,
) -> list[Change]

Compare two parse results (or plain data) and list what changed.

Change dataclass

Change(
    path: str,
    kind: str,
    before: Any = None,
    after: Any = None,
)

Discovery

supported_commands

supported_commands(
    platform: str | Platform | None = None,
) -> list[dict[str, Any]]

List the commands with dedicated parsers, optionally for one platform.

find_parser

find_parser(
    platform: str | Platform, command: str
) -> Resolution | None

Return which dedicated parser would handle command (None if none).

detect_platform

detect_platform(
    output: str = "", command: str | None = None
) -> Detection

Guess the platform that produced output (and/or accepts command).

Scoring combines prompt recognition, the command verb (display is a Huawei hallmark) and weighted fingerprints such as interface naming conventions. The winner must beat the runner-up by a margin, otherwise platform is None and the caller should ask the user.

list_platforms

list_platforms() -> list[Platform]

get_platform

get_platform(name: str | Platform) -> Platform

Return the :class:Platform for name (any alias, case insensitive).

Extending

register

register(
    platform: str, *patterns: str, intent: str | None = None
) -> Callable[[type[Parser]], type[Parser]]

Class decorator registering a :class:Parser for one or more command patterns.

Parser

Parser(
    params: dict[str, str] | None = None, command: str = ""
)

Base class for dedicated parsers.

Subclasses implement :meth:parse, returning JSON-serialisable data (dict or list). self.params holds values captured from the command pattern, e.g. {"vrf": "CUSTOMER-A"}.

Errors

exceptions

Exception hierarchy. Everything raised on purpose derives from :class:CliJsonError.

CliJsonError

Bases: Exception

Base class for all library errors.

ParserNotFound

ParserNotFound(
    platform: str,
    command: str,
    suggestions: list[str] | None = None,
)

Bases: CliJsonError, LookupError

Raised in strict mode when no dedicated parser supports a command.

ParseError

ParseError(parser: str, message: str)

Bases: CliJsonError

A dedicated parser failed on the given output.

DeviceError

Bases: CliJsonError

Problem talking to a live device (clijson.live).