API Reference
Core
Column metadata shared by the GUI, exporters, and help dialog.
- class pymtr.core.columns.ColumnDefinition(key, list_header, report_header, width, full_name, description, interpretation)
Definition of a displayed/exported metric column.
- Parameters:
key (str) – Stable internal column key.
list_header (str) – Header used by the GUI table.
report_header (str) – Header used by reports.
width (int) – Default GUI width in pixels.
full_name (str) – Expanded metric name for help text.
description (str) – Meaning of the metric.
interpretation (str) – Suggested interpretation guidance.
- pymtr.core.columns.ordered_columns(order=None)
Return columns in a validated order.
- Parameters:
order (list[str] | tuple[str, ...] | None) – Optional list of column keys.
- Returns:
Ordered column definitions.
- Return type:
list[ColumnDefinition]
Hop statistics and incremental metric calculations.
- class pymtr.core.hop.HopStats(index, address='', hostname='', sent=0, transit=0, received=0, total=0.0, last=0.0, best=0.0, worst=0.0, avg=0.0, ssd=0.0, gmean=0.0, jitter=0.0, javg=0.0, jmax=0.0, jint=0.0)
Statistics for a single route hop.
- Parameters:
index (int) – Zero-based hop index.
address (str) – IPv4 address returned by the probe.
hostname (str) – Reverse DNS name, if available.
sent (int)
transit (int)
received (int)
total (float)
last (float)
best (float)
worst (float)
avg (float)
ssd (float)
gmean (float)
jitter (float)
javg (float)
jmax (float)
jint (float)
- begin_probe()
Mark a probe as sent and in transit.
- Return type:
None
- property completed: int
Number of probes that are no longer in transit.
- property display_name: str
Host label that keeps both IP and DNS name visible.
- property drop: int
Dropped packet count, clamped to zero.
- end_probe()
Mark one in-transit probe as completed.
- Return type:
None
- property loss: float
Packet loss percentage, clamped to zero.
- record_reply(rtt_ms)
Record a received reply and update incremental metrics.
- Parameters:
rtt_ms (float) – Round-trip time in milliseconds.
- Return type:
None
- property stdev: float
Sample standard deviation of observed latency.
Metric formatting helpers.
- pymtr.core.metrics.column_value(hop, row_number, key, history_store=None)
Return the display/export value for a column key.
- Parameters:
hop (HopStats) – Hop statistics.
row_number (int) – One-based row number.
key (str) – Column key from the shared catalog.
history_store (HopHistoryStore | None)
- Returns:
Formatted value.
- Return type:
str
- pymtr.core.metrics.format_count(value)
Format an integer count.
- Parameters:
value (int)
- Return type:
str
- pymtr.core.metrics.format_metric(value)
Format a latency-like metric with one decimal place.
- Parameters:
value (float)
- Return type:
str
- pymtr.core.metrics.metric_numeric_value(hop, row_number, key, history_store=None)
Return the numeric value behind a column when one exists.
- Parameters:
hop (HopStats) – Hop statistics.
row_number (int) – One-based row number.
key (str) – Column key from the shared catalog.
history_store (HopHistoryStore | None) – Optional SQLite history used by derived percentile metrics.
- Returns:
Numeric value, or
Nonefor textual columns.- Return type:
float | None
Temporary SQLite storage for per-hop historical metrics.
- class pymtr.core.history.ChartSeries(key, label, unit, points)
Renderable series for one selected metric.
- Parameters:
key (str) – Metric key.
label (str) – Display label.
unit (str) – Metric unit.
points (list[tuple[int, float, str]]) –
(timestamp_epoch_ms, value, timestamp_local)points.
- class pymtr.core.history.HistoryStoreProtocol(*args, **kwargs)
Storage contract used by the GUI, reports, and trace session.
The active implementation remains SQLite. This protocol keeps callers independent from storage internals.
- close(remove=False)
Close the store.
- Parameters:
remove (bool)
- Return type:
None
- percentile_value(hop_index, metric_key)
Return the latest percentile value for a hop.
- Parameters:
hop_index (int)
metric_key (str)
- Return type:
float
- record_snapshot(cycle, hops, trace_id=None)
Record one visible trace snapshot.
- Parameters:
cycle (int)
hops (list[HopStats])
trace_id (str | None)
- Return type:
None
- samples(hop_index, metric_keys=None, start_epoch_ms=None, end_epoch_ms=None)
Return historical samples for a hop.
- Parameters:
hop_index (int)
metric_keys (list[str] | tuple[str, ...] | None)
start_epoch_ms (int | None)
end_epoch_ms (int | None)
- Return type:
list[HopHistorySample]
- time_bounds(hop_index)
Return the full timestamp range for a hop.
- Parameters:
hop_index (int)
- Return type:
tuple[int, int] | None
- class pymtr.core.history.HopHistorySample(timestamp_epoch_ms, timestamp_local, cycle, hop_index, ttl, address, hostname, values)
One historical metrics sample for a displayed hop.
- Parameters:
timestamp_epoch_ms (int) – Local computer time as epoch milliseconds.
timestamp_local (str) – Local computer timestamp for display.
cycle (int) – Trace cycle that produced this sample.
hop_index (int) – Zero-based hop index.
ttl (int) – One-based hop number.
address (str) – Displayed hop IP address.
hostname (str) – Displayed hop hostname.
values (dict[str, float]) – Metric values keyed by chart metric key.
- class pymtr.core.history.HopHistoryStore(path=None, session_id=None, target='')
Thread-safe temporary SQLite store for one trace history.
- Parameters:
path (Path | None)
session_id (str | None)
target (str)
- close(remove=False)
Close the SQLite connection and optionally remove the temp files.
- Parameters:
remove (bool)
- Return type:
None
- property disabled: bool
Return whether writes were disabled after a store failure.
- percentile_value(hop_index, metric_key)
Return the current historical percentile value for a hop.
Percentile metrics are intentionally derived from the temporary SQLite history instead of
HopStatsso they do not affect the incremental MTR-compatible statistics.- Parameters:
hop_index (int) – Zero-based hop index.
metric_key (str) – One of the keys in
PERCENTILE_METRICS.
- Returns:
Percentile value in milliseconds, or
0.0without data.- Return type:
float
- record_snapshot(cycle, hops, trace_id=None)
Record one visible snapshot produced by a trace cycle.
- Parameters:
cycle (int) – Trace cycle number.
hops (list[HopStats]) – Visible hop snapshots.
trace_id (str | None) – Optional telemetry trace identifier.
- Return type:
None
- samples(hop_index, metric_keys=None, start_epoch_ms=None, end_epoch_ms=None)
Read historical samples for a hop in timestamp order.
- Parameters:
hop_index (int) – Zero-based hop index.
metric_keys (list[str] | tuple[str, ...] | None) – Optional metric keys to include.
start_epoch_ms (int | None) – Optional inclusive viewport start.
end_epoch_ms (int | None) – Optional inclusive viewport end.
- Returns:
Historical samples.
- Return type:
list[HopHistorySample]
- time_bounds(hop_index)
Return the first and last timestamps for one hop.
- Parameters:
hop_index (int) – Zero-based hop index.
- Returns:
(start_ms, end_ms)orNonewhen no data exists.- Return type:
tuple[int, int] | None
- class pymtr.core.history.TimeViewport(start_ms, end_ms, full_start_ms, full_end_ms)
Visible timestamp range for a chart.
- Parameters:
start_ms (int) – Inclusive visible start timestamp.
end_ms (int) – Inclusive visible end timestamp.
full_start_ms (int) – Earliest timestamp available in the full history.
full_end_ms (int) – Latest timestamp available in the full history.
- pymtr.core.history.build_chart_series(samples, metric_keys, labels)
Convert history samples into per-metric renderable series.
- Parameters:
samples (list[HopHistorySample])
metric_keys (list[str] | tuple[str, ...])
labels (dict[str, str])
- Return type:
list[ChartSeries]
- pymtr.core.history.clamp_viewport(start_ms, end_ms, full_start_ms, full_end_ms, min_width_ms=1000)
Clamp a requested viewport to available history bounds.
- Parameters:
start_ms (int)
end_ms (int)
full_start_ms (int)
full_end_ms (int)
min_width_ms (int)
- Return type:
- pymtr.core.history.nearest_rank_percentile(values, percentile)
Calculate a nearest-rank percentile from observed values.
- Parameters:
values (list[float] | tuple[float, ...]) – Numeric samples.
percentile (int) – Percentile in the inclusive range
1to100.
- Returns:
The observed value at the nearest-rank position, or
0.0when there are no samples.- Return type:
float
- pymtr.core.history.normalize_chart_metric_keys(keys, default=('last', 'best', 'avg', 'worst', 'stdev', 'gmean', 'jitter', 'javg', 'jmax', 'jint', 'lp50', 'lp95', 'lp99', 'jp50', 'jp95', 'jp99'))
Return valid chart metric keys, preserving order and uniqueness.
- Parameters:
keys (list[str] | tuple[str, ...] | None)
default (tuple[str, ...])
- Return type:
list[str]
- pymtr.core.history.pan_viewport(viewport, delta_ms)
Move a viewport horizontally by
delta_ms.- Parameters:
viewport (TimeViewport)
delta_ms (int)
- Return type:
- pymtr.core.history.zoom_viewport(viewport, anchor_ms, factor)
Zoom a viewport around a timestamp anchor.
factorbelow1zooms in and above1zooms out.- Parameters:
viewport (TimeViewport)
anchor_ms (int)
factor (float)
- Return type:
Continuous trace session orchestration.
- class pymtr.core.session.ProbeAttempt(ttl, token)
A scheduled probe and the metadata needed to apply it deterministically.
- Parameters:
ttl (int)
token (int)
- class pymtr.core.session.TraceSession(target, settings, backend=None, history_store=None, ip_version=None, on_snapshot=None, on_status=None)
Manage a continuous trace loop.
- Parameters:
target (str) – Host name or IP address to trace.
settings (AppSettings) – Runtime settings.
backend (ProbeBackend | None) – Optional backend, primarily used by tests.
history_store (HopHistoryStore | None) – Optional temporary history store for chart data.
ip_version (int | None) – Optional IP family preference, either
4or6.on_snapshot (SnapshotCallback | None) – Callback invoked after hop updates.
on_status (StatusCallback | None) – Callback invoked for status messages.
- join(timeout=None)
Wait for the background trace loop to stop.
- Parameters:
timeout (float | None)
- Return type:
None
- start()
Start the background continuous trace loop.
- Return type:
None
- stop()
Request the trace loop to stop.
- Return type:
None
- trace_once()
Run one probe cycle synchronously.
- Return type:
None
Telemetry
OpenTelemetry-style JSON Lines logging for PyMTR debug sessions.
- pymtr.telemetry.configure(enabled, path='logs/pymtr-otel.jsonl')
Configure debug telemetry output.
The emitted JSON Lines records follow OpenTelemetry naming conventions for timestamps, trace/span identifiers, severity, body, resource, and attributes.
- Parameters:
enabled (bool) – Whether telemetry should be written.
path (str | Path) – Destination JSON Lines file.
- Return type:
None
- pymtr.telemetry.emit(severity_text, body, *, trace_id=None, span_id=None, attributes=None)
Emit one OpenTelemetry-style JSON log record.
- Parameters:
severity_text (str) – Text severity such as
INFOorERROR.body (str) – Event name or message body.
trace_id (str | None) – Optional trace identifier.
span_id (str | None) – Optional span identifier.
attributes (dict[str, Any] | None) – Event attributes.
- Return type:
None
- pymtr.telemetry.is_enabled()
Return whether telemetry is currently enabled.
- Return type:
bool
- pymtr.telemetry.new_span_id()
Create a 16-character OpenTelemetry span identifier.
- Return type:
str
- pymtr.telemetry.new_trace_id()
Create a 32-character OpenTelemetry trace identifier.
- Return type:
str
CLI and TUI
Command-line interface for PyMTR.
- pymtr.cli.build_parser()
Build the PyMTR command-line parser.
- Return type:
ArgumentParser
- pymtr.cli.main(argv=None, *, backend_factory=None, console=None)
Run the PyMTR CLI dispatcher.
- Parameters:
argv (Sequence[str] | None) – Optional argument vector.
backend_factory (Callable[[], ProbeBackend] | None) – Optional backend factory used by tests.
console (Console | None) – Optional Rich console used by tests.
- Returns:
Process exit code.
- Return type:
int
- pymtr.cli.render_snapshot_for_tests(hops, columns, history_store=None)
Render a plain console table for lightweight CLI tests.
- Parameters:
hops (Sequence[HopStats])
columns (Sequence[str])
history_store (HopHistoryStore | None)
- Return type:
str
- pymtr.cli.resolve_cli_columns(order, columns)
Resolve CLI column options into shared catalog keys.
- Parameters:
order (str | None)
columns (str | None)
- Return type:
list[str]
- pymtr.cli.run_gui(initial_host='')
Start the Tkinter GUI.
- Parameters:
initial_host (str) – Optional host to prefill in the Host field.
- Returns:
Process exit code.
- Return type:
int
- pymtr.cli.run_report_mode(target, settings, columns, args, backend_factory=None, console=None)
Run finite report mode and write requested exports.
- Parameters:
target (str)
settings (AppSettings)
columns (list[str])
args (Namespace)
backend_factory (Callable[[], ProbeBackend] | None)
console (Console | None)
- Return type:
int
- pymtr.cli.run_tui_mode(target, settings, columns, args, backend_factory=None, console=None)
Run the live terminal UI.
- Parameters:
target (str)
settings (AppSettings)
columns (list[str])
args (Namespace)
backend_factory (Callable[[], ProbeBackend] | None)
console (Console | None)
- Return type:
int
- pymtr.cli.settings_from_args(args)
Build runtime settings from CLI arguments without saving them.
- Parameters:
args (Namespace)
- Return type:
AppSettings
- pymtr.cli.write_requested_exports(target, snapshot, columns, args, history_store)
Write all export files requested by CLI report mode.
- Parameters:
target (str)
snapshot (list[HopStats])
columns (list[str])
args (Namespace)
history_store (HopHistoryStore)
- Return type:
None
Rich-based terminal UI helpers for PyMTR.
- pymtr.tui.build_rich_table(hops, columns, history_store=None, title='PyMTR')
Build a Rich table from a PyMTR snapshot.
- Parameters:
hops (Sequence[HopStats]) – Hop snapshots to render.
columns (Sequence[str]) – Ordered column keys.
history_store (HopHistoryStore | None) – Optional history store for percentile columns.
title (str) – Table title.
- Returns:
Rich table ready for console rendering.
- Return type:
Table
- pymtr.tui.run_live_tui(session, columns, console=None)
Run a continuous Rich live table until the user presses
Ctrl+C.- Parameters:
session (TraceSession) – Trace session to drive synchronously.
columns (Sequence[str]) – Ordered column keys to display.
console (Console | None) – Optional Rich console, primarily used by tests.
- Returns:
Last rendered snapshot.
- Return type:
list[HopStats]
Network
Backend contracts and backend selection.
Raised when a probe backend cannot be used on the current system.
- class pymtr.network.base.FakeProbeBackend(results)
Deterministic backend used by automated tests.
- Parameters:
results (dict[int, list[ProbeResult]]) – Mapping of TTL values to result sequences.
- close()
Fake backend has no resources to release.
- Return type:
None
- probe(target_ip, ttl, packet_size, timeout_ms, sequence)
Return the next scripted result for a TTL.
- Parameters:
target_ip (str)
ttl (int)
packet_size (int)
timeout_ms (int)
sequence (int)
- Return type:
- probe_batch(target_ip, requests)
Return scripted results for a batch of MTR-like probes.
- Parameters:
target_ip (str)
requests (list[ProbeRequest])
- Return type:
dict[int, ProbeResult]
- class pymtr.network.base.ProbeBackend(*args, **kwargs)
Protocol implemented by all probe backends.
- close()
Release backend resources.
- Return type:
None
- probe_batch(target_ip, requests)
Send multiple probes and return results keyed by request token.
- Parameters:
target_ip (str)
requests (list[ProbeRequest])
- Return type:
dict[int, ProbeResult]
- class pymtr.network.base.ProbeRequest(token, ttl, packet_size, timeout_ms, protocol='icmp', ip_version=4, port=33434)
Request for one MTR-like network probe.
- Parameters:
token (int) – Unique token used to correlate the eventual reply.
ttl (int) – Time-to-live or hop limit used for the probe.
packet_size (int) – Packet size requested by the session.
timeout_ms (int) – Probe-specific timeout in milliseconds.
protocol (str) – Probe protocol name, such as
icmp.ip_version (int) – IP family version, either
4or6.port (int) – Destination port for UDP/TCP probes.
- class pymtr.network.base.ProbeResult(ttl, address='', rtt_ms=None, reached=False, status='', details=<factory>)
Result returned by a single TTL probe.
- Parameters:
ttl (int) – TTL used for the probe.
address (str) – Responding hop address, if known.
rtt_ms (float | None) – Round-trip time in milliseconds.
reached (bool) – Whether the final target was reached.
status (str) – Backend-specific status text.
details (dict[str, Any]) – Backend diagnostics included only in debug telemetry.
- pymtr.network.base.select_backend()
Select the preferred runtime backend.
- Returns:
MTR-like packet helper backend.
- Raises:
BackendUnavailable – If no backend can be initialized.
- Return type:
DNS helpers for PyMTR.
- pymtr.network.dns.resolve_ipv6_address(host)
Return a factual IPv6 address for a host when one is directly known.
This helper is intentionally display-only. It does not alter the probe target resolution preference, reverse DNS cache, or route identity flow.
- Parameters:
host (str) – Hostname or IP address text.
- Returns:
IPv6 address text, or
Nonewhen unavailable.- Return type:
str | None
- pymtr.network.dns.resolve_target(host, ip_version=None)
Resolve a host name to an IP address.
- Parameters:
host (str) – Host name, IPv4 address, or IPv6 address.
ip_version (int | None) – Optional IP version preference, either
4or6.
- Returns:
IP address text.
- Raises:
socket.gaierror – If the host cannot be resolved.
- Return type:
str
- pymtr.network.dns.reverse_lookup(address)
Resolve an IPv4 address back to a hostname.
- Parameters:
address (str) – IP address text.
- Returns:
Hostname or the original address when reverse lookup fails.
- Return type:
str
Subprocess backend that talks to the PyMTR packet helper.
- class pymtr.network.packet_backend.PacketHelperBackend
Probe backend implemented through a long-running packet helper.
- close()
Stop the helper subprocess.
- Return type:
None
- ensure_supported(feature)
Ensure the helper supports a feature before tracing starts.
- Parameters:
feature (str)
- Return type:
None
- probe_batch(target_ip, requests)
Send a batch of probes and return results keyed by token.
- Parameters:
target_ip (str)
requests (list[ProbeRequest])
- Return type:
dict[int, ProbeResult]
Text protocol used by the PyMTR packet helper.
The protocol is intentionally close to the public mtr-packet contract:
each line starts with a numeric token, followed by a command or reply name and
zero or more key/value arguments. Tokens are the source of truth for
correlating replies that may arrive out of order.
- exception pymtr.network.packet_command.PacketCommandError
Raised when a helper protocol line cannot be parsed.
- class pymtr.network.packet_command.PacketMessage(token, name, arguments=<factory>)
Parsed packet-helper command or reply.
- Parameters:
token (int) – Numeric correlation token.
name (str) – Command or reply name.
arguments (dict[str, str]) – Key/value arguments.
- argument(name, default='')
Return an argument value with a default.
- Parameters:
name (str)
default (str)
- Return type:
str
- pymtr.network.packet_command.build_check_support(token, feature)
Build a
check-supportcommand.- Parameters:
token (int)
feature (str)
- Return type:
- pymtr.network.packet_command.build_reply(*, token, name, address='', ip_version=4, round_trip_time_us=None, support='', reason='')
Build a helper reply message.
- Parameters:
token (int)
name (str)
address (str)
ip_version (int)
round_trip_time_us (int | None)
support (str)
reason (str)
- Return type:
- pymtr.network.packet_command.build_send_probe(*, token, address, ip_version, protocol, ttl, packet_size, timeout_seconds, port)
Build a
send-probecommand.- Parameters:
token (int)
address (str)
ip_version (int)
protocol (str)
ttl (int)
packet_size (int)
timeout_seconds (float)
port (int)
- Return type:
- pymtr.network.packet_command.format_timeout(seconds)
Format timeout seconds without losing sub-second precision.
- Parameters:
seconds (float)
- Return type:
str
- pymtr.network.packet_command.parse_message(line)
Parse one helper protocol line.
- Parameters:
line (str) – Protocol line without a required trailing newline.
- Returns:
Parsed message.
- Raises:
PacketCommandError – If the line is malformed.
- Return type:
- pymtr.network.packet_command.serialize_message(message)
Serialize a message into one protocol line.
- Parameters:
message (PacketMessage)
- Return type:
str
In-flight probe registry for the packet helper.
- class pymtr.network.probe_registry.ProbeRegistry
Track probes by token and protocol-specific identity.
- add(state)
Add a new in-flight probe.
- Parameters:
state (ProbeState)
- Return type:
None
- complete_icmp(ip_version, identifier, sequence)
Complete an ICMP probe by echo identifier and sequence.
- Parameters:
ip_version (int)
identifier (int)
sequence (int)
- Return type:
ProbeState | None
- complete_ports(protocol, ip_version, local_port, remote_port)
Complete a UDP/TCP probe by embedded transport ports.
- Parameters:
protocol (str)
ip_version (int)
local_port (int)
remote_port (int)
- Return type:
ProbeState | None
- complete_token(token)
Remove and return a probe by token.
- Parameters:
token (int)
- Return type:
ProbeState | None
- expired(now=None)
Remove and return probes whose timeout has elapsed.
- Parameters:
now (float | None)
- Return type:
list[ProbeState]
- next_sequence()
Return the next MTR-like sequence number.
- Return type:
int
- class pymtr.network.probe_registry.ProbeState(token, protocol, ip_version, destination, ttl, sent_at, timeout_at, sequence, identifier=0, local_port=0, remote_port=0)
State for one in-flight network probe.
- Parameters:
token (int)
protocol (str)
ip_version (int)
destination (str)
ttl (int)
sent_at (float)
timeout_at (float)
sequence (int)
identifier (int)
local_port (int)
remote_port (int)
Protocol helpers for MTR-like packet probing.
- class pymtr.network.protocols.DecodedIcmp(ip_version, icmp_type, code, identifier=0, sequence=0, embedded_protocol=0, embedded_src_port=0, embedded_dst_port=0, embedded=False)
Decoded ICMP response metadata.
- Parameters:
ip_version (int)
icmp_type (int)
code (int)
identifier (int)
sequence (int)
embedded_protocol (int)
embedded_src_port (int)
embedded_dst_port (int)
embedded (bool)
- property status: str
Return the MTR-like status represented by this ICMP message.
- pymtr.network.protocols.build_icmp_echo(ip_version, identifier, sequence, payload)
Build an ICMP echo request packet.
- Parameters:
ip_version (int)
identifier (int)
sequence (int)
payload (bytes)
- Return type:
bytes
- pymtr.network.protocols.build_udp_payload(packet_size)
Build deterministic UDP payload bytes.
- Parameters:
packet_size (int)
- Return type:
bytes
- pymtr.network.protocols.checksum(data)
Calculate the Internet checksum for a byte sequence.
- Parameters:
data (bytes)
- Return type:
int
- pymtr.network.protocols.local_address_for(target_ip, ip_version)
Return the local address the OS would use to reach a target.
- Parameters:
target_ip (str)
ip_version (int)
- Return type:
str
- pymtr.network.protocols.parse_icmp_response(data, ip_version)
Parse an ICMP response for IPv4 or IPv6.
- Parameters:
data (bytes)
ip_version (int)
- Return type:
DecodedIcmp | None
Subprocess packet helper with an MTR-like text protocol.
- class pymtr.packet_helper.PacketHelper
MTR-like helper that sends probes and writes tokenized replies.
- run()
Run the helper event loop until stdin closes.
- Return type:
None
- class pymtr.packet_helper.TcpProbeSocket(token, sock, target_ip, ip_version)
Writable TCP socket associated with an in-flight probe.
- Parameters:
token (int)
sock (socket)
target_ip (str)
ip_version (int)
- pymtr.packet_helper.main()
Entry point used by
python -m pymtr.packet_helper.- Return type:
None
Export
Plain text report rendering.
- pymtr.export.text.render_header(columns)
Render the text header row.
- Parameters:
columns (list[ColumnDefinition])
- Return type:
str
- pymtr.export.text.render_text_report(hops, order=None, title='PyMTR statistics', history_store=None)
Render a support-friendly plain text report.
- Parameters:
hops (list[HopStats]) – Hop snapshots.
order (list[str] | None) – Optional column key order.
title (str) – Report title.
history_store (HopHistoryStore | None) – Optional history used for derived percentile metrics.
- Returns:
Text report.
- Return type:
str
CSV report rendering.
- pymtr.export.csv.render_csv_report(hops, order=None, history_store=None)
Render a CSV report with stable column order.
- Parameters:
hops (list[HopStats]) – Hop snapshots.
order (list[str] | None) – Optional column key order.
history_store (HopHistoryStore | None) – Optional history used for derived percentile metrics.
- Returns:
CSV content.
- Return type:
str
HTML report rendering.
- pymtr.export.html.render_html_report(hops, order=None, title='PyMTR statistics', history_store=None)
Render a simple HTML report.
- Parameters:
hops (list[HopStats]) – Hop snapshots.
order (list[str] | None) – Optional column key order.
title (str) – Report title.
history_store (HopHistoryStore | None) – Optional history used for derived percentile metrics.
- Returns:
HTML document.
- Return type:
str
Chart image and hop-detail export helpers.
- pymtr.export.chart.render_chart_image(series, title, width=1200, height=700, empty_message='No historical data yet')
Render historical metric series as a line-only chart image.
- Parameters:
series (list[ChartSeries]) – Metric series to render.
title (str) – Chart title.
width (int) – Output image width in pixels.
height (int) – Output image height in pixels.
empty_message (str) – Message drawn when no series points exist.
- Returns:
RGB Pillow image.
- Return type:
Image
- pymtr.export.chart.write_chart_html(path, title, image, snapshot_rows, live_rows)
Write a standalone HTML chart report for one hop.
- Parameters:
path (Path) – Destination file.
title (str) – Report title.
image (Image) – Rendered chart image.
snapshot_rows (list[tuple[str, str]]) – Snapshot metric label/value pairs.
live_rows (list[tuple[str, str]]) – Live metric label/value pairs.
- Return type:
None
- pymtr.export.chart.write_chart_jpg(path, image)
Write a chart image as JPEG.
- Parameters:
path (Path)
image (Image)
- Return type:
None
- pymtr.export.chart.write_chart_pdf(path, title, image, snapshot_rows, live_rows)
Write a PDF chart report for one hop.
- Parameters:
path (Path)
title (str)
image (Image)
snapshot_rows (list[tuple[str, str]])
live_rows (list[tuple[str, str]])
- Return type:
None
- pymtr.export.chart.write_chart_png(path, image)
Write a chart image as PNG.
- Parameters:
path (Path)
image (Image)
- Return type:
None
Full-session PDF report generation.
- pymtr.export.full_report.write_full_report_pdf(path, title, target, hops, history_store, column_order=None, metric_keys=None)
Write a PDF report for the current PyMTR session.
- Parameters:
path (Path) – Destination PDF path.
title (str) – Report title.
target (str) – Current trace target.
hops (list[HopStats]) – Visible hop snapshot from the current instance.
history_store (HopHistoryStore) – History store belonging to the current trace session.
column_order (list[str] | None) – Optional metric table order. Defaults to all catalog metrics.
metric_keys (list[str] | None) – Optional metric keys. Defaults to all historical metrics.
- Return type:
None
GUI
Main Tkinter window for PyMTR.
- class pymtr.gui.main_window.PyMTRWindow(texts, settings, initial_host='')
Main desktop window preserving the WinMTR workflow.
- Parameters:
texts (TextResources)
settings (AppSettings)
initial_host (str)
- pymtr.gui.main_window.default_report_export_dir()
Return the default folder for Generate FullReport exports.
- Return type:
Path
Canvas-based metrics grid used by the main PyMTR window.
- class pymtr.gui.metric_grid.MetricGrid(master, columns, display_columns, conditional_formats=None, column_widths=None, header_labels=None)
A small table widget with column reordering and per-cell formatting.
- Parameters:
master (tk.Misc)
columns (list[ColumnDefinition])
display_columns (list[str])
conditional_formats (dict[str, ConditionalFormatRule] | None)
column_widths (dict[str, int] | None)
header_labels (dict[str, str] | None)
- bind_double_click(callback)
Bind a callback fired after a row is double-clicked.
- Parameters:
callback (Callable[[Event], None])
- Return type:
None
- bind_selection(callback)
Bind a callback fired after row selection changes.
- Parameters:
callback (Callable[[Event], None])
- Return type:
None
- exists(iid)
Return whether a row identifier exists.
- Parameters:
iid (str)
- Return type:
bool
- focus(iid)
Keep API compatibility with
ttk.Treeviewcallers.- Parameters:
iid (str)
- Return type:
None
- selection()
Return the selected row identifier as a Treeview-like tuple.
- Return type:
tuple[str, …]
- selection_set(iid)
Select a row by identifier.
- Parameters:
iid (str)
- Return type:
None
- set_column_resize_callback(callback)
Set the callback used after a column width changes.
- Parameters:
callback (Callable[[str, int], None])
- Return type:
None
- set_column_widths(widths)
Replace user-resized column widths and redraw the table.
- Parameters:
widths (dict[str, int])
- Return type:
None
- set_conditional_formats(rules)
Replace conditional formatting rules and redraw the table.
- Parameters:
rules (dict[str, ConditionalFormatRule])
- Return type:
None
- set_display_columns(display_columns)
Set the visible column order.
- Parameters:
display_columns (list[str])
- Return type:
None
- set_header_context_callback(callback)
Set the callback used for right-clicks on column headers.
- Parameters:
callback (Callable[[str, int, int], None])
- Return type:
None
- set_header_labels(labels)
Replace header labels and redraw the table.
- Parameters:
labels (dict[str, str])
- Return type:
None
- set_reorder_callback(callback)
Set the callback used when a column is dropped in a new position.
- Parameters:
callback (Callable[[str, int], None])
- Return type:
None
- set_rows(rows)
Replace the grid rows and redraw the table.
- Parameters:
rows (list[MetricGridRow])
- Return type:
None
- visible_column_order()
Return the currently visible column keys.
- Return type:
list[str]
- class pymtr.gui.metric_grid.MetricGridRow(iid, values, numeric_values)
One rendered row in the metrics grid.
- Parameters:
iid (str) – Stable row identifier.
values (dict[str, str]) – Text values keyed by column key.
numeric_values (dict[str, float | None]) – Numeric values keyed by column key when available.
- pymtr.gui.metric_grid.conditional_color(rule, value)
Return the conditional warning color for a numeric value.
Values at or below the normal limit intentionally render with the default table color instead of the rule’s normal color, so only cells that exceed a configured threshold are visually emphasized.
- Parameters:
rule (ConditionalFormatRule)
value (float)
- Return type:
str
Conditional formatting dialog for numeric metric columns.
- class pymtr.gui.conditional_format_dialog.ConditionalFormatDialog(master, column, texts, current_rule, on_apply)
Edit conditional text colors and thresholds for one numeric column.
- Parameters:
master (tk.Misc)
column (ColumnDefinition)
texts (TextResources)
current_rule (ConditionalFormatRule | None)
on_apply (Callable[[ConditionalFormatRule | None], None])
Options dialog for editable PyMTR settings.
- class pymtr.gui.options_dialog.OptionsDialog(master, settings, texts, on_apply=None)
Dialog used to edit runtime and UI settings.
- Parameters:
master (tk.Misc) – Parent Tk widget.
settings (AppSettings) – Mutable settings object to update.
texts (TextResources) – Text resources used by the interface.
on_apply (Callable[[], None] | None) – Optional callback invoked after settings are saved.
License dialog for PyMTR.
- class pymtr.gui.license_dialog.LicenseDialog(master, texts)
Resizable dialog that displays the project license text.
- Parameters:
master (tk.Misc) – Parent Tk widget.
texts (TextResources) – Text resources containing the configured license type.
- pymtr.gui.license_dialog.build_license_display_text(texts, official_text=None)
Return license guidance followed by the official English text.
- Parameters:
texts (TextResources) – English text resources.
official_text (str | None) – Optional MIT license text override used by tests.
- Returns:
Display-ready license content.
- Return type:
str
- pymtr.gui.license_dialog.load_license_text(texts=None)
Load the repository
LICENSEfile.- Parameters:
texts (TextResources | None) – Optional text resources for the fallback message.
- Returns:
License text or a short fallback when the file cannot be found.
- Return type:
str
Metrics help dialog.
- class pymtr.gui.help_dialog.HelpDialog(master, texts)
Dialog containing metric descriptions and interpretation guidance.
- Parameters:
master (tk.Misc)
texts (TextResources)
- pymtr.gui.help_dialog.build_help_text(texts)
Return the English metrics help text without Tk formatting tags.
- Parameters:
texts (TextResources) – English text resources.
- Returns:
Display-ready plain text for tests and non-Tk consumers.
- Return type:
str
- pymtr.gui.help_dialog.iter_help_blocks(texts)
Return English help content blocks with optional Tk text tags.
- Parameters:
texts (TextResources) – English text resources.
- Returns:
Display text blocks and the optional tag used by the dialog.
- Return type:
tuple[tuple[str, str | None], …]
Hotkeys help dialog.
- class pymtr.gui.hotkeys_dialog.HotkeysDialog(master, texts)
Resizable dialog listing all application keyboard shortcuts.
- Parameters:
master (tk.Misc)
texts (TextResources)
Report issue guidance dialog for PyMTR.
- class pymtr.gui.report_issue_dialog.ReportIssueDialog(master, texts)
Resizable dialog explaining how to report actionable PyMTR issues.
- Parameters:
master (tk.Misc) – Parent Tk widget.
texts (TextResources) – English UI text resources.
Tk Canvas chart for temporary hop history metrics.
- class pymtr.gui.history_chart.HistoryChartFrame(master, history_store, hop_index, settings, texts=None)
Live chart frame for a hop’s historical metrics.
- Parameters:
master (tk.Misc)
history_store (HopHistoryStore)
hop_index (int)
settings (AppSettings)
texts (TextResources | None)
- selected_metrics()
Return the metric keys selected in this chart window.
- Return type:
list[str]
- pymtr.gui.history_chart.canvas_x_to_timestamp(x, viewport, left, plot_width)
Map a canvas X coordinate back into the visible viewport.
- Parameters:
x (int)
viewport (TimeViewport)
left (int)
plot_width (int)
- Return type:
int
- pymtr.gui.history_chart.downsample_chart_points(points, max_points=1600)
Return a bounded point list for Canvas rendering.
The history store keeps every sample for metrics and reports. This helper limits only the visual Canvas workload so large traces remain responsive.
- Parameters:
points (list[tuple[int, float, str]])
max_points (int)
- Return type:
list[tuple[int, float, str]]
- pymtr.gui.history_chart.live_follow_viewport(current, full_start_ms, full_end_ms)
Return a live-follow viewport that preserves the current zoom width.
- Parameters:
current (TimeViewport)
full_start_ms (int)
full_end_ms (int)
- Return type:
- pymtr.gui.history_chart.persist_chart_metric_selection(settings, selected)
Persist a non-empty chart metric selection.
- Returns:
Truewhen a selection was written.- Parameters:
settings (AppSettings)
selected (list[str])
- Return type:
bool
- pymtr.gui.history_chart.scrollbar_fractions(viewport)
Return horizontal scrollbar fractions for the visible viewport.
- Parameters:
viewport (TimeViewport)
- Return type:
tuple[float, float]
- pymtr.gui.history_chart.selected_chart_metric_keys(keys)
Return valid selected chart keys without applying a fallback metric.
This is intentionally different from settings normalization: a Hop Details window may be empty for temporary visual focus, but that empty state must not become the next global default.
- Parameters:
keys (list[str] | tuple[str, ...])
- Return type:
list[str]
- pymtr.gui.history_chart.timestamp_for_viewport_ratio(viewport, ratio)
Return the timestamp at a normalized position inside a viewport.
- Parameters:
viewport (TimeViewport)
ratio (float)
- Return type:
int
- pymtr.gui.history_chart.timestamp_to_canvas_x(timestamp_ms, viewport, left, plot_width)
Map a timestamp to the same X coordinate system used by the chart.
- Parameters:
timestamp_ms (int)
viewport (TimeViewport)
left (int)
plot_width (int)
- Return type:
float
- pymtr.gui.history_chart.viewport_from_scroll_fraction(viewport, fraction)
Move a viewport so its left edge matches a scrollbar fraction.
- Parameters:
viewport (TimeViewport)
fraction (float)
- Return type:
Hop properties dialog.
- class pymtr.gui.properties_dialog.PropertiesDialog(master, hop, texts, history_store=None, settings=None, latest_hop_provider=None, on_close=None)
Dialog showing details for a selected hop.
- Parameters:
master (tk.Misc)
hop (HopStats)
texts (TextResources)
history_store (HopHistoryStore | None)
settings (AppSettings | None)
latest_hop_provider (Callable[[int], HopStats | None] | None)
on_close (Callable[['PropertiesDialog'], None] | None)
- pymtr.gui.properties_dialog.default_chart_export_dir()
Return the default folder for Hop Details chart exports.
- Return type:
Path
- pymtr.gui.properties_dialog.hop_detail_rows(hop, timestamp_label=None, timestamp=None, history_store=None, *, texts=None, include_identity=True)
Return all metrics shown in the hop details dialog.
- Parameters:
hop (HopStats) – Hop whose current statistics should be displayed.
timestamp_label (str | None) – Optional timestamp label.
timestamp (datetime | None) – Optional local timestamp for this metric snapshot.
history_store (HopHistoryStore | None) – Optional historical store for percentile metrics.
texts (TextResources | None) – Optional English text resources.
include_identity (bool) – Include non-metric hop identity rows.
- Returns:
Label/value pairs in a stable troubleshooting-friendly order.
- Return type:
list[tuple[str, str]]
- pymtr.gui.properties_dialog.hop_detail_title(base_title, hop)
Return the hop details window title with the selected hop identity.
- Parameters:
base_title (str)
hop (HopStats)
- Return type:
str
- pymtr.gui.properties_dialog.hop_identity_rows(hop, texts=None)
Return one non-duplicated identity section for a hop.
- Parameters:
hop (HopStats) – Hop whose hostname and address should be displayed.
texts (TextResources | None) – Optional English text resources.
- Returns:
Label/value pairs for the Hop details section.
- Return type:
list[tuple[str, str]]
- pymtr.gui.properties_dialog.hop_metric_rows(hop, timestamp_label=None, timestamp=None, history_store=None)
Return only the snapshot/live metrics for a hop.
- Parameters:
hop (HopStats)
timestamp_label (str | None)
timestamp (datetime | None)
history_store (HopHistoryStore | None)
- Return type:
list[tuple[str, str]]
- pymtr.gui.properties_dialog.not_available_text(texts=None)
Return the English fallback text used for unavailable values.
- Parameters:
texts (TextResources | None)
- Return type:
str