Customize Console Commands

Register custom commands for the Console panel

Overview#

Console commands allow users to execute functions by typing commands in the Console panel. Commands start with / and can accept arguments.

Register a Command#

from witwin import Console
 
def greet(name: str = "World"):
    return f"Hello, {name}!"
 
Console.register_command("greet", greet, "Greet someone by name")

Users can then type in the Console:

/greet
/greet Alice

API Reference#

Console.register_command(
    name: str,           # Command name (without / prefix)
    handler: Callable,   # Function to execute
    description: str = "",
    extension_id: str = None  # For extension cleanup
)

Command Handler#

The handler function receives arguments as positional parameters:

def my_command(arg1: str = "default", arg2: int = 0):
    # Process command
    return "Result message"
 
Console.register_command("mycommand", my_command, "Description")

Return Value#

The return value is displayed in the Console:

def stats():
    return f"Objects: 42, Memory: 128MB"
 
Console.register_command("stats", stats, "Show statistics")
> /stats
Objects: 42, Memory: 128MB

Examples#

Simple Command#

from witwin import Console
 
def clear_cache():
    # Clear cache logic
    return "Cache cleared"
 
Console.register_command("clear_cache", clear_cache, "Clear the object cache")

Command with Arguments#

def spawn(object_type: str = "cube", count: int = 1):
    # Spawn objects
    return f"Spawned {count} {object_type}(s)"
 
Console.register_command("spawn", spawn, "Spawn objects: /spawn [type] [count]")

Usage:

/spawn cube 5
/spawn sphere

Command with Scene Access#

from witwin import Console
 
def list_objects():
    from witwin import Scene
    scene = Scene.get_current()
    names = [obj.name for obj in scene.objects]
    return f"Objects: {', '.join(names)}"
 
Console.register_command("list", list_objects, "List all scene objects")

Command with Results Output#

from witwin import Console, Results
import numpy as np
 
def plot_random(points: int = 100):
    x = np.random.randn(int(points))
    y = np.random.randn(int(points))
    Results.scatter(x.tolist(), y.tolist(), title="Random Points")
    Results.commit(message="Random scatter plot")
    return f"Plotted {points} random points"
 
Console.register_command("plot_random", plot_random, "Generate random scatter plot")

Debug Commands#

def debug_on():
    Console.log("Debug mode enabled")
    return "Debug mode: ON"
 
def debug_off():
    Console.log("Debug mode disabled")
    return "Debug mode: OFF"
 
Console.register_command("debug_on", debug_on, "Enable debug mode")
Console.register_command("debug_off", debug_off, "Disable debug mode")

Extension Commands#

When registering commands from an extension, provide the extension_id for cleanup:

# In your extension's __init__.py
EXTENSION_ID = "my_extension"
 
def my_command():
    return "Hello from extension"
 
Console.register_command(
    "ext_hello",
    my_command,
    "Extension greeting",
    extension_id=EXTENSION_ID
)

Unregister Commands#

# Unregister a single command
Console.unregister_command("greet")
 
# Unregister all commands from an extension
Console.unregister_extension_commands("my_extension")

Built-in Commands#

WiTwin includes these built-in commands:

CommandDescription
/helpList all available commands
/clearClear console output

Complete Example#

from witwin import Console, Results, Notifications
import numpy as np
 
EXTENSION_ID = "data_tools"
 
def generate_data(n: int = 100, noise: float = 0.1):
    """Generate sample data with noise."""
    x = np.linspace(0, 10, int(n))
    y = np.sin(x) + np.random.randn(int(n)) * float(noise)
    Results.plot(x.tolist(), y.tolist(), title=f"Sample Data (n={n}, noise={noise})")
    Results.commit(message=f"Generated data")
    return f"Generated {n} points with noise={noise}"
 
def analyze_data():
    """Analyze current data."""
    Console.log("Analyzing data...")
    # Analysis logic here
    return "Analysis complete"
 
def export_csv(filename: str = "data.csv"):
    """Export data to CSV."""
    Console.log(f"Exporting to {filename}...")
    Notifications.success("Export", f"Saved to {filename}")
    return f"Exported to {filename}"
 
def status():
    """Show current status."""
    return "Status: Ready | Objects: 5 | Memory: 64MB"
 
# Register all commands
Console.register_command("gen", generate_data, "Generate sample data: /gen [n] [noise]", EXTENSION_ID)
Console.register_command("analyze", analyze_data, "Analyze current data", EXTENSION_ID)
Console.register_command("export", export_csv, "Export to CSV: /export [filename]", EXTENSION_ID)
Console.register_command("status", status, "Show current status", EXTENSION_ID)

Usage:

> /help
Available commands:
  /gen [n] [noise] - Generate sample data
  /analyze - Analyze current data
  /export [filename] - Export to CSV
  /status - Show current status
 
> /gen 200 0.2
Generated 200 points with noise=0.2
 
> /status
Status: Ready | Objects: 5 | Memory: 64MB
 
> /export results.csv
Exported to results.csv