Command Infrastructure and Public Commands

Command specifications, parser construction helpers, command input handling, and top-level command modules.

Command Package

Command Definitions for the GONet Wizard CLI and GUI

This package is the declarative registry for all user-invoked entry points in GONet Wizard, supporting both traditional command-line execution and GUI-backed workflows (PyWebview + a unified local UI server).

Each command is implemented in a dedicated module (e.g. show, show_meta, run_dashboard) and exposes a COMMAND object of type CommandSpec describing its CLI signature. At runtime, the parser infrastructure wires these specs into an argparse.ArgumentParser tree and dispatches to a handler.

Beyond the CLI, commands can optionally return structured UI results (preview publishes, window-open requests, or both). This enables a single command implementation to work in:

  • terminal-only mode (print/side effects only), and/or

  • GUI mode (open windows and publish HTML previews via the unified UI server)

Infrastructure Overview

The command system is split into focused modules that together provide a declarative, extensible command tree with optional UI presentation:

Declarative Command Tree

This package declares the root PARSER object (a ParserSpec) describing the top-level CLI group. The centralized parser builder consumes PARSER to build the complete command hierarchy dynamically.

Top-level commands are collected in COMMANDS. Experimental nested command groups can be parked in the source tree without being registered in PARSER; for example, the remote-camera connect workflow is currently deferred and intentionally omitted from the public command tree.

Available Commands

GONet_Wizard.commands.show

Visualize one or more GONet files and channels using Plotly.

GONet_Wizard.commands.show_meta

Extract and display GONet file metadata as text or HTML.

GONet_Wizard.commands.extract

Extract pixel counts from GONet files using configurable ROI shapes.

GONet_Wizard.commands.run_dashboard

Launch the interactive Dash-based GONet Wizard dashboard in a managed window.

GONet_Wizard.commands.build_full_array

Build or process full-array products from GONet inputs.

GONet_Wizard.commands.split_raw

Convert RAW GONet JPEG files into standard TIFF and JPEG images.

GONet_Wizard.commands.gui

Launch the unified GUI launcher window.

Constants

COMMANDStuple

Tuple of top-level command modules registered under the root parser.

PARSERParserSpec

Root parser specification defining the command hierarchy for the CLI/GUI.

Specifications

Declarative CLI Specification Models

This module defines lightweight dataclass models used to describe the structure of the GONet Wizard command-line interface in a declarative way. These specifications are consumed by parser-construction utilities to build an argparse.ArgumentParser tree without duplicating argument wiring logic across command modules.

Classes

ParserSpec

Specification for a command group / subparser group (including nested groups).

CommandSpec

Specification for a single CLI command and its argument definitions.

class GONet_Wizard.commands.specs.ParserSpec(dest, help, args)[source]

Bases: object

Declarative specification for an argparse subparser group.

A ParserSpec describes a command group (e.g., top-level commands or a nested group) by defining the destination name under which argparse stores the selected command, a help string, and a configuration dictionary describing available commands and nested parser groups.

dest

Attribute name under which argparse stores the chosen command.

Type:

str

help

Help string for this subparser group.

Type:

str

args

Parser-group configuration. Common keys include:

  • "commands": iterable of command modules/objects (each exposing COMMAND)

  • "subparsers": nested parser group specifications

Type:

dict

class GONet_Wizard.commands.specs.CommandSpec(name, help, args)[source]

Bases: object

Declarative specification for a single CLI command.

A CommandSpec defines a command name, its help text, and a sequence of argument specifications that are passed through to argparse.ArgumentParser.add_argument() during parser construction.

Command modules typically expose a COMMAND instance of this class and a cli_handler(args) function. Parser builders may attach the handler via set_defaults(handler=...) to enable dispatch after argument parsing.

name

Command name.

Type:

str

help

Help string for the command.

Type:

str

args

A list of argparse.ArgumentParser.add_argument() specification dictionaries.

Type:

list of dict

Parser Construction

CLI Parser Construction Utilities

This module provides helper functions to build an argparse command tree from declarative command and parser specifications. It supports both simple leaf commands (no nested subcommands) and hierarchical command groups via recursive subparser construction.

The resulting parsers are configured to dispatch to command handlers, with handlers wrapped through wrap_handler_for_ui() to enable consistent execution from both CLI and UI entry points.

Functions

register_simple_subcommand()

Register a single leaf command specification on a subparser group.

build_subparser()

Recursively construct a parser and its nested subparsers from a package-defined PARSER specification.

GONet_Wizard.commands.parser_builder.register_simple_subcommand(subparsers, cmd)[source]

Register a single simple command (no nested subparsers) to a subparser group.

This function reads the COMMAND specification from cmd to create a corresponding subparser, add its arguments, and attach a handler when the command exposes a cli_handler attribute.

Parameters:
  • subparsers (argparse._SubParsersAction) – The subparser group to which the command parser will be added.

  • cmd (object) – A command module or object exposing a COMMAND specification and optionally a cli_handler callable.

Return type:

None

Returns:

None

Raises:
  • KeyError – If an argument specification declares "flags" but does not provide a valid sequence of flag strings.

  • AttributeError – If cmd does not provide a COMMAND attribute.

GONet_Wizard.commands.parser_builder.build_subparser(parser, package)[source]

Recursively build subparsers from a package defining a PARSER object.

This function attaches a subparser group to parser using the destination and help text defined by package.PARSER. It then registers any leaf commands listed under package.PARSER.args["commands"] and recursively constructs nested subcommand groups from package.PARSER.args["subparsers"].

The subparser group is created with parser_class=parser.__class__ so that all generated subparsers inherit the same parser type as the parent. This is required when the root parser is a custom subclass (e.g., SmartArgumentParser) and parse errors must be handled consistently across the entire command tree. Without this override, argparse would instantiate subparsers as plain argparse.ArgumentParser instances, bypassing custom error/exit behavior implemented by the parent parser class.

Parameters:
  • parser (argparse.ArgumentParser) – The parser to augment with subparsers.

  • package (object) – A package-like object exposing a PARSER specification describing available commands and nested parser groups.

Return type:

ArgumentParser

Returns:

argparse.ArgumentParser – The updated parser instance.

Raises:
  • AttributeError – If package does not define a PARSER attribute.

  • KeyError – If a nested subparser specification references a parser_name that is not present in the current subparser group’s choices.

Smart Parser

Smart argparse Wrapper for Classified Parse Errors

This module defines a custom argparse.ArgumentParser subclass that replaces argparse’s default SystemExit-based error handling with structured, typed exceptions.

The parser classifies parse failures into broad categories (e.g. missing required arguments vs. unknown arguments) and preserves contextual information such as the original argv and the inferred command token sequence. This enables higher-level CLI logic to decide how to handle parse failures, including routing specific cases to GUI-backed workflows.

Constants

_CURRENT_ARGV

Process-local copy of the current argument vector, used as a fallback for subparsers that are not explicitly initialized with an argv reference.

Functions

set_current_argv()

Store the current argument vector for later retrieval during parse errors.

_guess_cmd_tokens()

Extract a best-effort command token sequence from an argument vector.

Classes

SmartArgumentParser

Subclass of argparse.ArgumentParser that raises CliParseError instead of exiting the process.

GONet_Wizard.commands.smart_parser.set_current_argv(argv)[source]

Store the current argument vector for parse-time error handling.

This function records a process-local copy of argv so that subparsers created by argparse (which do not receive custom constructor arguments) can still access the full invocation context when reporting parse errors.

Parameters:

argv (Sequence of str) – Argument vector representing the current CLI invocation (typically sys.argv[1:]).

Return type:

None

Returns:

None – This function does not return a value.

Raises:

None

GONet_Wizard.commands.smart_parser.normalize_negative_option_values(parser, argv)[source]

Normalize negative numeric option values before argparse sees them.

argparse accepts negative numeric values for options in many simple cases, but values containing punctuation, such as -90,180, can be mistaken for an option token. Rewriting --angles -90,180 as --angles=-90,180 removes the ambiguity while preserving the user’s intended value.

Return type:

list[str]

class GONet_Wizard.commands.smart_parser.SmartArgumentParser(*args, argv=None, **kwargs)[source]

Bases: ArgumentParser

Argument parser that raises structured exceptions on parse failure.

This class overrides argparse’s default error and exit behavior to raise CliParseError instead of calling sys.exit. Each error is classified into a ParseErrorKind and includes contextual information about the original invocation.

_argv

Argument vector explicitly associated with this parser instance, if provided at construction time.

Type:

Optional of Sequence of str

parse_args(args=None, namespace=None)[source]

Parse arguments after normalizing ambiguous negative option values.

This preserves standard argparse behavior while allowing invocations such as --angles -90,90 to work as users expect.

error(message)[source]

Handle an argparse parsing error.

This method classifies the failure based on the error message and raises a CliParseError containing the classification and contextual information.

Parameters:

message (str) – Error message produced by argparse.

Return type:

None

Returns:

None

Raises:

CliParseError – Always raised to signal a classified parse failure.

exit(status=0, message=None)[source]

Intercept argparse exit calls.

This override ensures that any attempt by argparse to terminate the process results in a CliParseError instead.

Parameters:
  • status (int, optional) – Exit status requested by argparse.

  • message (Optional of str, optional) – Optional message associated with the exit.

Return type:

None

Returns:

None

Raises:

CliParseError – Always raised to prevent process termination.

Argparse Errors

CLI Parse Error Models

This module defines small, typed models used to represent argument-parsing failures without terminating the process.

The primary consumer is the CLI entry point, which can catch these exceptions and choose between standard terminal error output and UI routing behavior.

Classes

ParseErrorKind

Enumeration describing broad categories of parse failures.

CliParseError

Exception carrying a classified parse failure along with context such as the argv that triggered it and the best-effort extracted command token sequence.

class GONet_Wizard.commands.argparse_errors.ParseErrorKind(value)[source]

Bases: str, Enum

Classification categories for CLI parsing failures.

MISSING_REQUIRED

A required argument was not provided (e.g., missing required positional).

Type:

str

UNKNOWN_ARGS

One or more tokens were not recognized by the parser (e.g., unknown flag).

Type:

str

OTHER

Any other parse failure that does not fall in the above categories.

Type:

str

exception GONet_Wizard.commands.argparse_errors.CliParseError(kind, message, argv=None, cmd_tokens=None)[source]

Bases: Exception

Exception raised to report a classified CLI parsing failure.

This exception is intended to replace argparse’s default SystemExit-based error handling so callers can decide how to present failures (e.g., printing usage to stderr or opening a GUI form page).

kind

Classification of the parsing failure.

Type:

ParseErrorKind

message

Human-readable argparse error message associated with the failure.

Type:

str

argv

Argument vector that triggered the failure, if available.

Type:

Optional of Sequence of str

cmd_tokens

Best-effort extracted command token sequence (e.g., ("show",) or ("connect", "snap")), if available.

Type:

Optional of Sequence of str

CLI Core

Command-Line Interface Core Compatibility Layer

This module serves as a compatibility shim for the GONet Wizard command-line infrastructure. Historically, it hosted CLI specifications, input expansion helpers, parser construction utilities, and UI preview integration in a single location.

As the CLI architecture evolved, these responsibilities were split into dedicated modules to improve separation of concerns and maintainability:

This module re-exports the public API from those modules to preserve backward compatibility and avoid widespread changes to existing imports.

Constants

None

Classes

ParserSpec

Declarative specification for CLI parser groups.

CommandSpec

Declarative specification for individual CLI commands.

ExpandFilenames

argparse.Action for expanding CLI file inputs.

ExtensionFilterError

Exception raised when extension-based filtering yields no files.

PublishRequest

Request to publish HTML preview content.

WindowRequest

Request to open or focus a UI window.

Functions

expand_inputs()

Expand CLI file tokens into concrete filesystem paths.

filter_by_ext()

Filter file paths by allowed extensions.

maybe_present_ui_result()

Realize UI results and start the webview loop if needed.

realize_ui_result()

Normalize and apply UI result(s).

wrap_handler_for_ui()

Wrap a CLI handler to support UI result emission.

build_subparser()

Recursively construct an argparse subparser tree.

register_simple_subcommand()

Register a leaf command on a subparser group.

class GONet_Wizard.commands.cli_core.ParserSpec(dest, help, args)[source]

Bases: object

Declarative specification for an argparse subparser group.

A ParserSpec describes a command group (e.g., top-level commands or a nested group) by defining the destination name under which argparse stores the selected command, a help string, and a configuration dictionary describing available commands and nested parser groups.

dest

Attribute name under which argparse stores the chosen command.

Type:

str

help

Help string for this subparser group.

Type:

str

args

Parser-group configuration. Common keys include:

  • "commands": iterable of command modules/objects (each exposing COMMAND)

  • "subparsers": nested parser group specifications

Type:

dict

class GONet_Wizard.commands.cli_core.CommandSpec(name, help, args)[source]

Bases: object

Declarative specification for a single CLI command.

A CommandSpec defines a command name, its help text, and a sequence of argument specifications that are passed through to argparse.ArgumentParser.add_argument() during parser construction.

Command modules typically expose a COMMAND instance of this class and a cli_handler(args) function. Parser builders may attach the handler via set_defaults(handler=...) to enable dispatch after argument parsing.

name

Command name.

Type:

str

help

Help string for the command.

Type:

str

args

A list of argparse.ArgumentParser.add_argument() specification dictionaries.

Type:

list of dict

class GONet_Wizard.commands.cli_core.ExpandFilenames(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

argparse.Action to expand CLI filename tokens into concrete paths.

This action normalizes user-provided input arguments that may include:

  • individual file paths

  • directories (non-recursive expansion)

  • wildcard patterns (e.g. *.tiff)

  • comma-separated lists of the above

The resolved paths are stored on the destination attribute as a list of pathlib.Path.

None
exception GONet_Wizard.commands.cli_core.ExtensionFilterError[source]

Bases: ValueError

Raised when extension-based filtering returns no files.

This exception indicates that an extension allowlist was applied to a set of candidate paths but no paths matched.

Notes

This is a subclass of ValueError to communicate invalid user input in CLI contexts.

GONet_Wizard.commands.cli_core.expand_inputs(tokens)[source]

Expand input tokens into a flat list of file paths.

Tokens may refer to explicit files, directories (expanded non-recursively), glob patterns, or comma-separated lists of these. The returned list preserves first-seen order while removing duplicates.

Parameters:

tokens (list of str) –

Input tokens that may include:

  • individual file paths

  • directories (non-recursive expansion)

  • wildcard patterns (e.g. *.tiff)

  • comma-separated lists of the above

Return type:

List[Path]

Returns:

list of pathlib.Path – A flat list of expanded file paths as pathlib.Path objects.

Raises:

FileNotFoundError – If any token (or comma-separated sub-token) does not match one or more existing files.

GONet_Wizard.commands.cli_core.filter_by_ext(paths, exts)[source]

Filter a list of file paths by extension.

This function normalizes the provided extension allowlist (case-insensitive, with or without leading dots) and returns the subset of paths whose pathlib.Path.suffix matches.

Parameters:
  • paths (list of pathlib.Path) – List of file paths to filter.

  • exts (list of str) – List of allowed file extensions (with or without leading dot). Example: ['.tiff', '.tif', '.json']

Return type:

List[Path]

Returns:

list of pathlib.Path – Filtered list of file paths that match the allowed extensions.

Raises:

.ExtensionFilterError – If no files match the allowed extensions.

class GONet_Wizard.commands.cli_core.PublishRequest(channel, html, title=None)[source]

Bases: object

Request to publish HTML into the PreviewManager under a channel.

channel

Preview channel name.

Type:

str

html

Full HTML document (e.g. Plotly fig.to_html(full_html=True) output).

Type:

str

title

Preview title stored for the channel.

Type:

str, optional

class GONet_Wizard.commands.cli_core.WindowRequest(key, spec, publish=None)[source]

Bases: object

Request to open/focus a window under a stable key.

A window request may optionally include a PublishRequest, allowing preview content to be published before the window is shown.

key

Window identity key used by the window manager registry.

Type:

str

spec

Window specification (title/url/size).

Type:

WindowSpec

publish

If provided, publish preview HTML before opening/focusing the window.

Type:

PublishRequest, optional

GONet_Wizard.commands.cli_core.maybe_present_ui_result(cmd_name, result, *, port=5050, debug_webview=False)[source]

Realize any UI result and start the webview loop if windows were requested.

Parameters:
  • cmd_name (str) – Command name used for legacy string results.

  • result (object) – Value returned by a command handler.

  • port (int, optional) – Port for the unified UI server. Defaults to 5050.

  • debug_webview (bool, optional) – If True, start the webview loop with debugging enabled.

Return type:

None

Returns:

None

Raises:

RuntimeError – If UI realization requires starting the unified UI server and startup fails.

GONet_Wizard.commands.cli_core.realize_ui_result(cmd_name, result, *, port)[source]

Apply UI result(s) and return whether any window was requested.

This function normalizes a handler return value and then: - publishes preview HTML when requested - ensures windows exist (or are focused) when requested - starts the unified UI server only when needed for preview-backed windows

Parameters:
  • cmd_name (str) – Command name used for legacy string results.

  • result (object) – Value returned by a command handler.

  • port (int) – Port for the unified UI server used by preview-backed windows.

Return type:

bool

Returns:

boolTrue if at least one WindowRequest was realized, otherwise False.

Raises:

RuntimeError – If the unified UI server cannot be started when required.

GONet_Wizard.commands.cli_core.wrap_handler_for_ui(cmd)[source]

Wrap a command handler so it can emit UI results from a CLI invocation.

The returned function calls cmd.cli_handler and then interprets its return value using maybe_present_ui_result(). This allows commands to return:

  • None (no UI action)

  • str (legacy HTML preview; channel = COMMAND.name)

  • PublishRequest (publish only)

  • WindowRequest (open/focus a window, optional publish)

  • a list or tuple containing any mix of the above

Parameters:

cmd (object) – Command module or object exposing a cli_handler callable and optionally a COMMAND specification.

Returns:

collections.abc.Callable – A handler compatible with argparse dispatch that accepts an argparse.Namespace and performs any requested UI actions.

Raises:

AttributeError – If cmd does not define cli_handler.

GONet_Wizard.commands.cli_core.build_subparser(parser, package)[source]

Recursively build subparsers from a package defining a PARSER object.

This function attaches a subparser group to parser using the destination and help text defined by package.PARSER. It then registers any leaf commands listed under package.PARSER.args["commands"] and recursively constructs nested subcommand groups from package.PARSER.args["subparsers"].

The subparser group is created with parser_class=parser.__class__ so that all generated subparsers inherit the same parser type as the parent. This is required when the root parser is a custom subclass (e.g., SmartArgumentParser) and parse errors must be handled consistently across the entire command tree. Without this override, argparse would instantiate subparsers as plain argparse.ArgumentParser instances, bypassing custom error/exit behavior implemented by the parent parser class.

Parameters:
  • parser (argparse.ArgumentParser) – The parser to augment with subparsers.

  • package (object) – A package-like object exposing a PARSER specification describing available commands and nested parser groups.

Return type:

ArgumentParser

Returns:

argparse.ArgumentParser – The updated parser instance.

Raises:
  • AttributeError – If package does not define a PARSER attribute.

  • KeyError – If a nested subparser specification references a parser_name that is not present in the current subparser group’s choices.

GONet_Wizard.commands.cli_core.register_simple_subcommand(subparsers, cmd)[source]

Register a single simple command (no nested subparsers) to a subparser group.

This function reads the COMMAND specification from cmd to create a corresponding subparser, add its arguments, and attach a handler when the command exposes a cli_handler attribute.

Parameters:
  • subparsers (argparse._SubParsersAction) – The subparser group to which the command parser will be added.

  • cmd (object) – A command module or object exposing a COMMAND specification and optionally a cli_handler callable.

Return type:

None

Returns:

None

Raises:
  • KeyError – If an argument specification declares "flags" but does not provide a valid sequence of flag strings.

  • AttributeError – If cmd does not provide a COMMAND attribute.

Input Expansion

CLI Input Expansion and File Extension Filtering

This module provides reusable utilities for expanding command-line file inputs into concrete filesystem paths. It supports common CLI input patterns including single files, non-recursive directory expansion, glob patterns, and comma-separated token lists, while preserving input order and removing duplicates.

These helpers are used primarily by argparse-based commands to normalize user input before downstream processing (e.g., reading GONet files or JSON outputs).

Classes

ExtensionFilterError

Exception raised when extension-based filtering yields no results.

ExpandFilenames

argparse.Action that expands CLI tokens into a list of pathlib.Path objects.

Functions

expand_inputs()

Expand file and directory tokens into a flat, de-duplicated list of paths.

filter_by_ext()

Filter a list of paths by allowed file extensions.

exception GONet_Wizard.commands.inputs.ExtensionFilterError[source]

Bases: ValueError

Raised when extension-based filtering returns no files.

This exception indicates that an extension allowlist was applied to a set of candidate paths but no paths matched.

Notes

This is a subclass of ValueError to communicate invalid user input in CLI contexts.

class GONet_Wizard.commands.inputs.ExpandFilenames(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

argparse.Action to expand CLI filename tokens into concrete paths.

This action normalizes user-provided input arguments that may include:

  • individual file paths

  • directories (non-recursive expansion)

  • wildcard patterns (e.g. *.tiff)

  • comma-separated lists of the above

The resolved paths are stored on the destination attribute as a list of pathlib.Path.

None
GONet_Wizard.commands.inputs.expand_inputs(tokens)[source]

Expand input tokens into a flat list of file paths.

Tokens may refer to explicit files, directories (expanded non-recursively), glob patterns, or comma-separated lists of these. The returned list preserves first-seen order while removing duplicates.

Parameters:

tokens (list of str) –

Input tokens that may include:

  • individual file paths

  • directories (non-recursive expansion)

  • wildcard patterns (e.g. *.tiff)

  • comma-separated lists of the above

Return type:

List[Path]

Returns:

list of pathlib.Path – A flat list of expanded file paths as pathlib.Path objects.

Raises:

FileNotFoundError – If any token (or comma-separated sub-token) does not match one or more existing files.

GONet_Wizard.commands.inputs.filter_by_ext(paths, exts)[source]

Filter a list of file paths by extension.

This function normalizes the provided extension allowlist (case-insensitive, with or without leading dots) and returns the subset of paths whose pathlib.Path.suffix matches.

Parameters:
  • paths (list of pathlib.Path) – List of file paths to filter.

  • exts (list of str) – List of allowed file extensions (with or without leading dot). Example: ['.tiff', '.tif', '.json']

Return type:

List[Path]

Returns:

list of pathlib.Path – Filtered list of file paths that match the allowed extensions.

Raises:

.ExtensionFilterError – If no files match the allowed extensions.

UI Bridge

CLI-to-UI Result Bridging Utilities

This module defines a small result protocol that allows CLI command handlers to optionally request UI behavior (publishing HTML previews and opening/focusing windows) without hard-coupling command modules to UI implementation details.

Command handlers may return legacy HTML strings (backward compatible) or structured request objects. Results are normalized and then realized by publishing preview content to the unified UI server and/or ensuring a window exists via the window manager. If windows are requested, the webview event loop is started.

Classes

PublishRequest

Request to publish an HTML document into the preview manager under a channel.

WindowRequest

Request to open/focus a window under a stable key, optionally publishing preview HTML first.

Functions

realize_ui_result()

Normalize and apply UI result(s), returning whether a window was requested.

maybe_present_ui_result()

Apply UI result(s) and start the webview loop if needed.

wrap_handler_for_ui()

Wrap a command cli_handler so it can return UI results and be handled consistently from the CLI.

class GONet_Wizard.commands.ui_bridge.PublishRequest(channel, html, title=None)[source]

Bases: object

Request to publish HTML into the PreviewManager under a channel.

channel

Preview channel name.

Type:

str

html

Full HTML document (e.g. Plotly fig.to_html(full_html=True) output).

Type:

str

title

Preview title stored for the channel.

Type:

str, optional

class GONet_Wizard.commands.ui_bridge.WindowRequest(key, spec, publish=None)[source]

Bases: object

Request to open/focus a window under a stable key.

A window request may optionally include a PublishRequest, allowing preview content to be published before the window is shown.

key

Window identity key used by the window manager registry.

Type:

str

spec

Window specification (title/url/size).

Type:

WindowSpec

publish

If provided, publish preview HTML before opening/focusing the window.

Type:

PublishRequest, optional

GONet_Wizard.commands.ui_bridge.realize_ui_result(cmd_name, result, *, port)[source]

Apply UI result(s) and return whether any window was requested.

This function normalizes a handler return value and then: - publishes preview HTML when requested - ensures windows exist (or are focused) when requested - starts the unified UI server only when needed for preview-backed windows

Parameters:
  • cmd_name (str) – Command name used for legacy string results.

  • result (object) – Value returned by a command handler.

  • port (int) – Port for the unified UI server used by preview-backed windows.

Return type:

bool

Returns:

boolTrue if at least one WindowRequest was realized, otherwise False.

Raises:

RuntimeError – If the unified UI server cannot be started when required.

GONet_Wizard.commands.ui_bridge.maybe_present_ui_result(cmd_name, result, *, port=5050, debug_webview=False)[source]

Realize any UI result and start the webview loop if windows were requested.

Parameters:
  • cmd_name (str) – Command name used for legacy string results.

  • result (object) – Value returned by a command handler.

  • port (int, optional) – Port for the unified UI server. Defaults to 5050.

  • debug_webview (bool, optional) – If True, start the webview loop with debugging enabled.

Return type:

None

Returns:

None

Raises:

RuntimeError – If UI realization requires starting the unified UI server and startup fails.

GONet_Wizard.commands.ui_bridge.wrap_handler_for_ui(cmd)[source]

Wrap a command handler so it can emit UI results from a CLI invocation.

The returned function calls cmd.cli_handler and then interprets its return value using maybe_present_ui_result(). This allows commands to return:

  • None (no UI action)

  • str (legacy HTML preview; channel = COMMAND.name)

  • PublishRequest (publish only)

  • WindowRequest (open/focus a window, optional publish)

  • a list or tuple containing any mix of the above

Parameters:

cmd (object) – Command module or object exposing a cli_handler callable and optionally a COMMAND specification.

Returns:

collections.abc.Callable – A handler compatible with argparse dispatch that accepts an argparse.Namespace and performs any requested UI actions.

Raises:

AttributeError – If cmd does not define cli_handler.

Build Full Array Command

CLI command for building full-array GONet products.

The build_full_array command converts one or more RAW GONet .jpg files into full-array .npz products. It delegates the image-processing work to GONet_Wizard.GONet_utils.src.gonet.analysis_utils.full_array.build_full_array() and keeps this module focused on CLI concerns: input expansion, extension filtering, output-name selection, logging configuration, and parsing optional channel weights.

The command is primarily intended for scripted preprocessing before downstream analysis or visualization.

Constants

COMMAND

Declarative command specification used by the shared parser builder and GUI form generator.

Functions

parse_channel_weights()

Convert the --weights CLI string into a channel-to-weight mapping.

cli_handler()

Execute the command after argparse has populated the namespace.

GONet_Wizard.commands.build_full_array.parse_channel_weights(weights)[source]

Parse comma-separated channel weights from the CLI.

The --weights option accepts strings such as "red=0.25,green1=0.5,green2=0.5,blue=0.25". This helper converts that text representation into the mapping expected by build_full_array().

Parameters:

weights (str, optional) – Comma-separated name=value pairs. If None, no custom channel weights are applied. Empty entries are ignored.

Return type:

dict[str, float] | None

Returns:

dict or None – Mapping from channel name to floating-point weight, or None when no weights were provided.

Raises:

ValueError – If an entry is missing the = separator, has an empty channel name, or contains a value that cannot be converted to float.

GONet_Wizard.commands.build_full_array.cli_handler(args)[source]

CLI handler for the build_full_array command.

The input argument is expanded using expand_inputs(), and filtered to include only RAW .jpg files. For each input file, the full-array image is built using build_full_array() with the specified parameters.

If multiple input files are provided and an outfile is specified, the outfile is treated as a suffix to be appended to each output file name.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Return type:

None

Returns:

None

Extract Command

GONet Pixel Extraction Command-Line Module

This module provides command-line utility functions to extract pixel counts from GONet image files. It supports different geometric selection shapes (e.g., circles, rectangles, annuli, and free-form shapes) for region-of-interest definition. The extraction can be triggered either through direct parameters or by launching an interactive GUI.

The module validates user-provided parameters for the selected shape and ensures that the extraction process is performed correctly. Results are saved to a JSON file, with automatic handling of file overwrites.

The command is declared via the COMMAND constant, which specifies the argument structure used by the centralized parser builder. When invoked from the CLI, the parser dispatches directly to cli_handler(), which translates the parsed argparse.Namespace into a call to the reusable plotting function.

Constants

  • COMMAND : CommandSpec object for the extract command.

Functions

validate_output_file()

Validate the output file path and ensure it does not overwrite an existing file.

comma_separated_pair()

Parse and validate a string representing two comma-separated integers.

extract_counts_from_GONet()

Perform counts extraction from one or more GONet files, using shape parameters provided by the user or launching the extraction GUI.

GONet_Wizard.commands.extract.validate_output_file(output, output_type)[source]

Validate the output file path and ensure it does not overwrite an existing file.

If the file already exists, an index is appended or incremented to create a unique filename.

Parameters:
  • output (str) – Path to the output file.

  • output_type (str) – Type of the output file, either “json” or “csv”.

Return type:

str

Returns:

tuple of str – A unique output file path and the output type.

Raises:

ValueError – If the output file path is invalid.

GONet_Wizard.commands.extract.comma_separated_pair(value, name)[source]

Parse and validate a string containing two comma-separated integers.

This function splits the provided string by commas, converts both parts to integers, and verifies that exactly two integers are present.

Parameters:
  • value (str) – String containing two integers separated by a comma (e.g., “100,200”).

  • name (str) – The name of the parameter (used in error messages).

Returns:

tuple of int – A tuple containing the two parsed integers.

Raises:

ValueError – If the input cannot be parsed into exactly two integers.

GONet_Wizard.commands.extract.parse_float_argument(value, name)[source]

Parse a numeric CLI argument and report the offending option name.

Parameters:
  • value (object) – Raw argument value to parse.

  • name (str) – Argument destination name, without leading dashes.

Returns:

float – Parsed floating-point value.

Raises:

ValueError – If value cannot be converted to a number.

GONet_Wizard.commands.extract.extract_counts_from_GONet(files, red=False, green=False, blue=False, shape=None, center=None, radius=None, sides=None, inner_radius=None, outer_radius=None, angles=None, output=None, output_type=None)[source]

Extract pixel counts from one or more GONet image files.

Depending on the provided shape parameter, the function validates associated geometric arguments (e.g. center, radius, sides, …) and performs counts extraction from the specified regions. If no shape is given or shape is set to ‘free’, the interactive extraction GUI is launched.

Parameters:
  • files (str or list of str) – Path(s) to one or more GONet image files to process.

  • red (bool, optional) – If True, extract counts from the red channel. Defaults to False.

  • green (bool, optional) – If True, extract counts from the green channel. Defaults to False.

  • blue (bool, optional) – If True, extract counts from the blue channel. Defaults to False.

  • shape (str, optional) –

    Shape of the extraction region. Supported values:

    • ”circle”: Requires center and radius.

    • ”rectangle”: Requires center and sides.

    • ”annulus”: Requires center, radius or inner_radius and outer_radius.

    • ”free” or None: Launch the interactive extraction GUI.

  • center (str, optional) – Center coordinates of the region, as “x,y” (pixels).

  • radius (float, optional) – Radius of the region (pixels) for “circle” or “annulus” shapes.

  • sides (str, optional) – Side lengths of the rectangle as “width,height” (pixels).

  • inner_radius (float, optional) – Inner radius (pixels) for the “annulus” shape. Either inner_radius or radius must be provided for annulus.

  • outer_radius (float, optional) – Outer radius (pixels) for the “annulus” shape.

  • angles (str, optional) – Start and end angles in degrees, as “start_angle,end_angle”. Defaults to “-180,180”.

  • output (str, optional) – Name of the output JSON file.

  • output_type (str, optional) – Type of the output file, either “json” or “csv”. Defaults to “json

Return type:

str | None

Returns:

str or None – Absolute path to the written output file, or None when the extraction is cancelled before writing output.

Raises:

ValueError – If required parameters for the chosen shape are missing or invalid.

Notes

  • If none of red, green, or blue are True, all channels will be extracted by default.

GONet_Wizard.commands.extract.cli_handler(args)[source]

Dispatch the extraction command from parsed CLI arguments.

When no explicit shape is supplied, or when the shape is "interactive", this handler launches the Dash-based extraction GUI and returns a WindowRequest for the shared UI runtime. Otherwise, it runs the non-interactive extraction workflow directly and writes JSON or CSV output through extract_counts_from_GONet().

Parameters:

args (argparse.Namespace) – Parsed command-line arguments produced from COMMAND.

Returns:

WindowRequest or None – A window request when launching the interactive extraction GUI. Returns None after a non-interactive extraction run.

Raises:

ExtensionFilterError – If the supplied filenames do not include any supported GONet image files.

Split RAW Command

CLI command for splitting RAW GONet JPEG files into standard images.

The split_raw command reads one or more original GONet RAW .jpg files and writes standard image products next to each input by default:

  • a 16-bit TIFF file (<stem>.tiff), and

  • a standard 8-bit JPEG file (<stem>.jpeg).

When an output directory is supplied, the command keeps products organized in separate tiffs and jpegs subdirectories. TIFF products do not apply white balance by default so their pixel values remain as faithful as possible to the RAW data for scientific extraction. JPEG products keep white balance enabled by default because they are usually intended for visual inspection.

The image loading and writing are delegated to GONet_Wizard.GONet_utils.GONetFile, which already knows how to parse GONet RAW JPEG files and export the processed RGB channels. This module keeps the command-layer behavior focused on CLI/GUI arguments, path handling, and safe overwrite checks.

Constants

COMMAND

Declarative command specification used by the shared parser builder and GUI form generator.

Functions

output_paths_for_raw()

Resolve the TIFF and JPEG output paths for one input file.

split_raw_file()

Convert a single RAW input file into the requested output products.

split_raw_files()

Convert a sequence of RAW input files.

cli_handler()

Execute the command after argparse has populated the namespace.

The SplitRawOutput helper is a small return container used internally by the command implementation. The public API documentation focuses on the command specification and conversion helpers because those are the stable integration points.

GONet_Wizard.commands.split_raw.output_paths_for_raw(input_file, outdir=None, output_format='both')[source]

Resolve standard TIFF/JPEG output paths for one RAW input file.

By default, outputs are written next to the input. TIFF outputs use <stem>.tiff and JPEG outputs use <stem>.jpeg so the generated JPEG does not overwrite the source RAW .jpg file. When outdir is supplied, TIFF outputs are written under outdir/tiffs and JPEG outputs under outdir/jpegs.

Parameters:
  • input_file (str or pathlib.Path) – Source RAW GONet JPEG file.

  • outdir (str or pathlib.Path, optional) – Base directory in which outputs should be written. If omitted, the input file’s parent directory is used.

  • output_format (str, optional) – Which product(s) to create: "both" (default), "tiff", or "jpeg".

Return type:

SplitRawOutput

Returns:

SplitRawOutput – Named tuple containing the source path and requested output paths.

GONet_Wizard.commands.split_raw.split_raw_file(input_file, outdir=None, output_format='both', overwrite=False, tiff_white_balance=False, jpeg_white_balance=True)[source]

Convert one RAW GONet JPEG file into standard image products.

Parameters:
  • input_file (str or pathlib.Path) – Source RAW GONet JPEG file.

  • outdir (str or pathlib.Path, optional) – Base output directory. If omitted, outputs are written next to the input. If supplied, products are written under tiffs and jpegs subfolders.

  • output_format (str, optional) – Which product(s) to create: "both" (default), "tiff", or "jpeg".

  • overwrite (bool, optional) – If True, existing outputs may be replaced. Defaults to False.

  • tiff_white_balance (bool, optional) – Whether to apply metadata white-balance gains to TIFF outputs. Defaults to False so TIFF pixel counts remain close to the RAW data.

  • jpeg_white_balance (bool, optional) – Whether to apply metadata white-balance gains to JPEG outputs. Defaults to True for visually useful JPEG products.

Return type:

SplitRawOutput

Returns:

SplitRawOutput – Paths written for this input file.

GONet_Wizard.commands.split_raw.split_raw_files(input_files, outdir=None, output_format='both', overwrite=False, tiff_white_balance=False, jpeg_white_balance=True)[source]

Convert multiple RAW GONet JPEG files into standard image products.

Parameters:
  • input_files (iterable of str or pathlib.Path) – Source RAW GONet JPEG files.

  • outdir (str or pathlib.Path, optional) – Base output directory for all products. If omitted, each input’s parent directory is used. If supplied, products are written under tiffs and jpegs subfolders.

  • output_format (str, optional) – Which product(s) to create: "both" (default), "tiff", or "jpeg".

  • overwrite (bool, optional) – If True, existing outputs may be replaced. Defaults to False.

  • tiff_white_balance (bool, optional) – Whether to apply metadata white-balance gains to TIFF outputs. Defaults to False.

  • jpeg_white_balance (bool, optional) – Whether to apply metadata white-balance gains to JPEG outputs. Defaults to True.

Return type:

list[SplitRawOutput]

Returns:

list of SplitRawOutput – Paths written for each input file.

GONet_Wizard.commands.split_raw.cli_handler(args)[source]

CLI handler for the split_raw command.

The handler prints a terminal-friendly summary and intentionally returns None. Returning an HTML-like string would be interpreted by the shared CLI UI bridge as a preview request, which would open an unnecessary window for this terminal-only conversion command.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments produced from COMMAND.

Return type:

None

Returns:

None – Feedback is emitted to stdout so both the terminal and GUI fake terminal receive the same summary.

Raises:

ExtensionFilterError – If the supplied inputs do not include supported RAW JPEG files.

Show Metadata Command

GONet Metadata Display Command

This module implements the show_meta CLI command, which extracts and displays metadata from one or more GONet image files. Output can be rendered either as plain text (for terminal use) or as HTML suitable for display in GUI contexts.

The command is declared via the COMMAND specification and dispatched through cli_handler(). Core formatting is handled by show_metadata(), which returns a rendered string without printing so callers can decide how to present the result.

Constants

COMMAND

CommandSpec defining the show_meta command.

Classes

_EmitBuffer

Internal line buffer that renders accumulated output as text or HTML.

Functions

show_metadata()

Extract and format metadata for one or more GONet files as text or HTML.

cli_handler()

CLI entry point for show_meta.

_render_value_html()

Render a Python value as HTML, recursively formatting containers.

_dict_to_table()

Render a mapping as an HTML table.

_list_to_table()

Render a list/sequence as inline HTML or a table, depending on content.

GONet_Wizard.commands.show_meta.show_metadata(files, *, as_html=False, pprint_indent=4, pprint_width=100)[source]

Extract and format metadata for one or more GONet files.

This function performs no printing. It returns a rendered string (text or HTML) so that callers may choose to print it, display it in a UI, or write it to disk.

Parameters:
  • files (str or Sequence of str) – A single file path or a sequence of file paths pointing to GONet files.

  • as_html (bool, optional) – If True, return the output as HTML. Defaults to False.

  • pprint_indent (int, optional) – Indentation passed to pprint.pformat(). Defaults to 4.

  • pprint_width (int, optional) – Width passed to pprint.pformat(). Defaults to 100.

Return type:

str

Returns:

str – Rendered output as a string (text by default, HTML if as_html=True).

Raises:

ValueError – If files is empty.

GONet_Wizard.commands.show_meta.save_metadata_pdf(files, save_path)[source]

Save the metadata shown by show_meta to a PDF file.

Parameters:
  • files (str or sequence of str) – Input GONet files whose metadata should be written.

  • save_path (str) – Requested PDF output path. .pdf is added automatically when omitted.

Return type:

str

Returns:

str – Final path written to disk.

Raises:

RuntimeError – If the ReportLab PDF backend is unavailable or the PDF cannot be written.

GONet_Wizard.commands.show_meta.cli_handler(args)[source]

CLI handler for the show_meta command.

This handler filters the provided inputs to supported file types and calls show_metadata(). If --html is set, it returns the rendered HTML string so a higher-level UI wrapper can capture it; otherwise it prints the text output to stdout.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments. Expected to provide filenames and an optional html flag.

Return type:

Optional[str]

Returns:

str or None – Rendered HTML string if --html is set; otherwise None after printing text output.

Raises:

.ExtensionFilterError – If none of the provided paths match the supported extensions.

Dashboard Command

GONet Dashboard Launcher Command

This module defines the dashboard CLI command used to launch the interactive GONet Wizard dashboard. The command prepares and validates input data paths, starts (or reuses) a Dash server instance, and requests that the dashboard be opened in a managed UI window.

Input paths may refer to directories or individual files and are expanded using shared CLI utilities. Only supported data formats are forwarded to the dashboard backend.

The command is declared via the COMMAND specification and dispatched through cli_handler(), which returns a WindowRequest for UI presentation.

Constants

COMMAND

CommandSpec defining the dashboard command and its CLI arguments.

Functions

cli_handler()

CLI entry point that prepares inputs, starts the dashboard server, and opens the dashboard window.

GONet_Wizard.commands.run_dashboard.cli_handler(args)[source]

CLI handler for launching the GONet dashboard.

This handler expands and normalizes input paths, filters supported data files, ensures that the dashboard server is running, and returns a WindowRequest instructing the UI layer to open the dashboard window.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments. Expected attributes include input, debug, and port.

Returns:

WindowRequest – A request to open the GONet Wizard Dashboard window.

Raises:
  • .ExtensionFilterError – If no input files match the supported extensions.

  • RuntimeError – If the dashboard server cannot be started.

GUI Command

GONet GUI Launcher Command

This module defines the gui CLI command, which launches the GONet Wizard graphical user interface. When invoked, the command ensures that the unified local UI server is running and opens the main launcher window using the window-management infrastructure.

The command is declared via the COMMAND specification and dispatched through cli_handler(), which returns a WindowRequest to open the launcher window.

Constants

COMMAND

CommandSpec defining the gui command.

Functions

cli_handler()

CLI entry point that starts the UI server and opens the launcher window.

GONet_Wizard.commands.gui.cli_handler(args)[source]

CLI handler for launching the GONet GUI.

This handler ensures that the unified UI server is running on the requested port and returns a WindowRequest instructing the UI layer to open the main launcher window.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments. Expected to provide a port attribute specifying the UI server port.

Return type:

WindowRequest

Returns:

WindowRequest – A request to open the GONet Launcher window.

Raises:

RuntimeError – If the unified UI server cannot be started.

Deferred Camera Commands

The remote-camera command modules are kept in the source tree as deferred, experimental functionality. They are documented separately so their status is clear and they do not get confused with the core image-processing workflow.

GONet Connect Command.

This module defines the experimental connect command specification.

The remote-camera workflow is currently deferred and intentionally not registered in the public GONet Wizard command tree. The COMMAND constant is kept so the SSH workflow can be revived later or split into a separate remote-control package without rebuilding the command specification.

Constants

  • COMMAND : CommandSpec object for the connect command.

Subcommands for the connect Command

This package contains the experimental remote-camera helpers originally planned for a nested connect command. These helpers perform remote operations on a GONet device over SSH, such as triggering imaging or terminating running processes.

The remote-camera workflow is currently deferred and intentionally not registered in the public GONet Wizard command tree. The PARSER object is kept here so the workflow can be revived later or moved into a separate remote control package without reconstructing the command specification from scratch.

Parser Specification

The PARSER defined here specifies the following:

  • dest="connect_subcommand" The argparse attribute where the chosen subcommand name will be stored.

  • help The help text that would be shown if the experimental connect group were registered.

  • args={"commands": COMMANDS} Registers the snap and terminate command modules—each of which provides a CommandSpec and a CLI handler.

This declarative structure allows the CLI builder to recursively attach this subpackage under the main connect command with no manual argparse wiring.

Remote Snapshot Command for GONet Devices

This module implements the experimental snap remote-camera helper. The remote-camera workflow is currently deferred and is not registered in the public GONet Wizard command tree. The helper can execute the gonet4.py imaging script on a GONet device, upload configuration files, stream live output, and download newly created images.

The command is declared via the COMMAND constant, a CommandSpec describing the CLI argument structure. When parsed by the centralized CLI builder, this command is wired to cli_handler(), which adapts the parsed argparse.Namespace to the core execution function take_snapshot().

The underlying operation uses the ssh_connect() decorator from ssh_utils to automatically manage SSH connections, ensuring that each command runs with a valid paramiko client and that the connection is safely closed afterward.

Functions

GONet_Wizard.commands.connect_commands.snap.list_remote_files(ssh, folder)[source]

List files in a remote folder using SSH.

Parameters:
  • ssh (paramiko.client.SSHClient) – An active SSH client connection to the remote GONet device.

  • folder (str) – Path to the remote folder to list.

Return type:

set

Returns:

set – A set of filenames found in the remote folder.

GONet_Wizard.commands.connect_commands.snap.get_local_file_hash(filepath, algo='sha256')[source]

Compute the hash of a local file.

Parameters:
  • filepath (str) – Path to the local file.

  • algo (str, optional) – Hashing algorithm to use (default is ‘sha256’).

Return type:

str

Returns:

str – The computed hash as a hexadecimal string.

GONet_Wizard.commands.connect_commands.snap.get_remote_file_hash(ssh, remote_path, algo='sha256')[source]

Compute the hash of a remote file using SSH.

Parameters:
  • ssh (paramiko.client.SSHClient) – An active SSH client connection.

  • remote_path (str) – Path to the remote file.

  • algo (str, optional) – Hashing algorithm (default is ‘sha256’).

Return type:

str | None

Returns:

str or None – The remote file’s hash, or None if the file does not exist or cannot be read.

GONet_Wizard.commands.connect_commands.snap.upload_if_different(ssh, local_path, remote_path)[source]

Upload a file only if it differs from the remote version.

Parameters:
  • ssh (paramiko.client.SSHClient) – SSH connection to the GONet device.

  • local_path (str) – Path to the local file.

  • remote_path (str) – Destination path on the remote device.

Return type:

None

Returns:

None

GONet_Wizard.commands.connect_commands.snap.run_remote_script_with_live_output(ssh, command)[source]

Run a remote command and stream stdout in real time.

Parameters:
Return type:

None

Returns:

None

GONet_Wizard.commands.connect_commands.snap.take_snapshot(ssh, config_file_path=None)[source]

Run the GONet imaging script remotely and download new files.

This function: - Checks current files in the image folder - Optionally uploads a config file if provided - Executes gonet4.py on the remote device - Downloads any newly created image files to the local machine

Parameters:
  • ssh (paramiko.client.SSHClient) – SSH connection (automatically provided by the decorator).

  • config_file_path (str, optional) – Local path to a configuration file to be used with gonet4.py.

Return type:

None

Returns:

None

Notes

  • Files are downloaded to the folder defined by LOCAL_OUTPUT_FOLDER.

  • Requires appropriate environment variables as defined in GONet_Wizard.commands.settings.GONetConfig.

GONet_Wizard.commands.connect_commands.snap.cli_handler(args)[source]

CLI handler for the snap command.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Return type:

None

Returns:

None

Remote Termination of Imaging Processes on a GONet Device

This module implements the terminate_imaging subcommand of the GONet Wizard CLI, allowing users to remotely stop imaging activity on a GONet device. This includes clearing scheduled tasks, killing active gonet4.py processes, and resetting the device’s status directory.

The command is declared through the COMMAND constant, a CommandSpec describing the subcommand’s name and help text. When registered by the centralized parser builder, this command dispatches to cli_handler(), which invokes the core remote operation terminate_imaging().

SSH operations are handled by the ssh_connect() decorator from ssh_utils, which automatically establishes and tears down an SSH connection, ensuring safe and consistent remote execution.

Functions

GONet_Wizard.commands.connect_commands.terminate.terminate_imaging(ssh)[source]

Terminate remote imaging activity and remove scheduling tasks.

This function connects via SSH to the remote GONet device and performs the following: - Clears the crontab (removing all scheduled tasks) - Kills any remaining gonet4.py processes - Deletes contents of /home/pi/Tools/Status/ - Creates a marker file to indicate imaging is terminated and disabled

Parameters:

ssh (paramiko.client.SSHClient) – An active SSH connection provided by the GONet_Wizard.commands.connect.ssh_connect() decorator.

Return type:

None

Returns:

None

Notes

  • The ssh_connect decorator handles connection and disconnection.

  • If crontab removal or process termination fails, a warning is printed.

GONet_Wizard.commands.connect_commands.terminate.cli_handler(args)[source]

CLI handler to terminate remote imaging.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments containing the necessary parameters.

Return type:

None

Returns:

None

SSH Connection Utilities for GONet Remote Access.

This module defines a decorator for safely managing SSH connections to a remote GONet device. It abstracts away the connection lifecycle, allowing decorated functions to focus solely on their task with an active paramiko.client.SSHClient instance.

Environment

Uses credentials from GONet_Wizard.settings.GONetConfig:

  • GONET_USER

  • GONET_PASSWORD

Functions

  • ssh_connect() : Decorator for establishing an SSH connection before calling a remote operation.

GONet_Wizard.commands.connect_commands.ssh_utils.ssh_connect(func)[source]

Decorator for establishing an SSH connection before calling a remote operation.

This decorator wraps a function that requires a live SSH connection. It manages: - Setting up the SSH client - Connecting to the given GONet device IP - Passing the connected SSH client to the decorated function - Automatically closing the connection afterward

Parameters:

func (Callable[[paramiko.client.SSHClient, Any], Any]) – A function that expects a connected SSH client as its first argument.

Return type:

Callable[[str, Any], Any]

Returns:

Callable[[str, Any], Any] – A new function that takes the GONet device IP address and any additional arguments. The SSH connection is established using the environment-configured credentials.

Raises:

Exception – If the SSH connection fails for any reason (auth, network, etc.), the exception is propagated.

Example

>>> @ssh_connect
... def list_home(ssh):
...     _, stdout, _ = ssh.exec_command("ls ~")
...     print(stdout.read().decode())
>>> list_home("192.168.1.101")