Skip to main content

xnano

An extremely nano terminal experience for Python, built on ratatui.

License Downloads Python Versions CodSpeed Built With Ratatui

Documentation · Learn · API Reference · Examples · Contribution Guide

Eight cards in a terminal, each playing one of the effects of xnano

xnano is a terminal framework for Python. You write content anywhere on the screen in one line, and what you wrote stays live: change its text, color or position at any time, and the screen follows.

import xnano

with xnano.open() as terminal:
    terminal.write('Hello, world!', x='center', y='center')
    terminal.run(stop_on='q')

Try It

The demo shows the widgets, effects and input in one program. Run it without installing anything, with uv:

uvx xnano

Pictures and sound are optional extras. To see and hear them in the demo:

uvx --from "xnano[image,audio]" xnano

The same command reads a file. On a terminal it opens a viewer with scrolling, search and links that you can click. In a pipe it prints the document.

uvx xnano README.md

It shows Markdown, text, JSON, tables (.csv, .tsv), PDFs, pictures and sound. --theme NAME chooses the colors, for example xnano-night or github-light.

Or install xnano and run the same demo:

pip install xnano
python -m xnano

Why xnano

The key features are:

  • Quick to start: The first program is four lines of code: import, open a terminal, write to it, run it.
  • Live: write() returns a placement. Change its text, its color or its position, and the screen follows. You write no redraw code.
  • Simple layout: A position or a size is a number of cells, a percentage, or a word such as 'center'. It holds when the window changes size.
  • Interactive: A hook is a plain function that runs on a key, a click, or a tick of the clock.
  • Complete: Widgets, effects and pixel art and images are written the same way as text.
  • Sound: Play notes, melodies and audio files on built-in instruments, in time with the clock, and read the level of the microphone.
  • Runs anywhere: xnano.open() takes the whole window, or a few rows below your prompt. xnano.new() draws into memory, to print or to test.
  • Fast: Layout and drawing run in Rust, on ratatui.
  • Compatible: Works with rich and textual, in both directions.

Installation

pip install xnano

Supported platforms

  • Python: 3.10 to 3.14.
  • Linux: x86_64 and aarch64, with glibc or musl.
  • macOS: Intel and Apple silicon.
  • Windows: x86_64.
  • WebAssembly: Pyodide, in a browser. A browser has no terminal, so a canvas from xnano.new() draws into memory there, and images and sound are not available.

Every platform has pre-built wheels, so you do not need a Rust toolchain.

Optional extras

Images and sound are optional extras. When you use a feature whose extra is missing, xnano tells you which one to install.

pip install "xnano[image]"  # pictures: .png, .jpg, .gif, .webp
pip install "xnano[audio]"  # sound: the speaker and the microphone
pip install "xnano[pdf]"  # the text of PDF files, for `xnano FILE` and `xnano.view`

On Linux, playing sound on a device needs ALSA (libasound). Composing and rendering sound work without a device everywhere.

Quick Start

Write to the terminal

Create a file main.py with:

import xnano

with xnano.open() as terminal:
    terminal.write('Hello, world!', x='center', y='center')
    terminal.run(stop_on='q')
hello-world

Run it with python main.py. Hello, world! appears in the middle of your terminal window, and stays there until you press q. The program:

  • opens a live terminal with xnano.open(), which takes over the whole window (give it a height to draw in a region below your prompt instead),
  • writes text with terminal.write(), at a position such as 'center',
  • keeps running with terminal.run() until one of its stop_on keys is pressed.

React to input

Now make the text change color when you click it:

import xnano

# `mouse=True` turns on mouse events
with xnano.open(mouse=True) as terminal:
    greeting = terminal.write('Hello, world!', x='center', y='center')

    # a hook runs a function when something happens, and a hook on a placement only
    # hears the events inside its own cells
    @greeting.hook(on='mouse')
    def change_color(context: xnano.Context):
        # the button is down from the press to the release: a click gives one new color,
        # and a drag across the text gives a new color at every step
        if context.mouse.is_down:
            greeting.color.fg.random()

    terminal.run(stop_on='q')
click-to-change-color

Move from one screen to the next

terminal.run() can return while the terminal stays open, so a program can have several steps. A key of end_on ends the run, and so does end_run() from a hook. A key of stop_on stops the terminal itself, and terminal.is_running tells the two apart.

import xnano

with xnano.open(height=3) as terminal:
    message = terminal.write('press enter to start', x='center', y='center')

    # `enter` ends this run: the terminal stays open, and the program goes on
    terminal.run(stop_on='q', end_on='enter')

    # after `q` the terminal is closed, so only go on while it is running
    if terminal.is_running:
        message.text = 'started: press q to quit'
        terminal.run(stop_on='q')

Features

Every example below is a complete program: copy it into a file and run it. Press q to leave the live ones. The Learn guides cover each feature step by step.

Layout

Positions and sizes take a number of cells, a percentage, or a word such as 'center' or 'bottom'. Percentages and words are kept, so content stays where you put it when the window changes. A canvas from xnano.new() draws into memory, so it can be printed without a live terminal. Learn more.

import xnano

# `layout='row'` gives everything written on the canvas an equal share of its width,
# and `x` and `y` place each piece inside its own share
with xnano.new(width='100%', height=7, layout='row') as canvas:
    canvas.write(
        'left panel', x='left', y='bottom', border='plain', foreground=(255, 0, 0)
    )
    canvas.write(
        'center panel',
        x='center',
        y='center',
        border='rounded',
        foreground='black',
        background='#f0f0f0',
    )
    canvas.write('right panel', x='right', y='top', border='thick', foreground='blue')

    # render one frame of the screen as colored text, and print it
    print(canvas.render(format='ansi'))
composing-content

Live content

write() returns a placement whose text and colors you can read and change at any time. Learn more.

import xnano

# each service's response time, and its requests over the last 30 seconds
services = {
    'api': ('41 ms', '▂▃▃▅▃▂▃▅▆▅▃▂▃▅▆▅▃▂▂▃▅▃▂▃▅▆▅▃▂▃'),
    'web': ('870 ms', '▃▅▆▅▃▂▂▃▅▇██▇▇█▇▅▆▇██▇▆▇█▇▆▅▆▇'),
    'worker': ('12 ms', '▁▁▂▁▁▃▁▁▁▂▅▂▁▁▁▂▁▁▃▂▁▁▁▂▁▁▁▂▃▁'),
}

# a canvas from `xnano.new()` needs no live terminal: `width='100%'` fills the window
with xnano.new(width='100%', height=7) as canvas:
    screen = canvas.screen
    screen.write('services', bold=True)
    screen.write(f'{screen.width}×{screen.height} cells', x='right', y=0, dim=True)

    cards = {}
    for index, (name, (latency, graph)) in enumerate(services.items()):
        cards[name] = screen.write(
            ['● online', f'p95 {latency}', graph],
            x=f'{index * 34}%',
            y=1,
            width='32%',
            border='rounded',
            title=name,
            foreground='green',
        )

    # `write()` returns a live placement: its text and colors can change at any time
    cards['web'].text = cards['web'].text.replace('● online', '▲ slow responses')
    cards['web'].color.fg = 'yellow'

    # and they can be read back, like any other value
    healthy = sum(card.text.startswith('●') for card in cards.values())
    screen.write(f'{healthy} of {len(cards)} services healthy', y='bottom', dim=True)

    print(screen.render(format='ansi'))
screen

Effects

Every placement has fx, with one method for each effect of tachyonfx. Effects run on the clock of the terminal, so they pause when it pauses. Learn more.

import xnano

with xnano.open(height=6) as terminal:
    card = terminal.write(
        'xnano',
        border='rounded',
        padding={'horizontal': 4, 'vertical': 1},
        foreground='magenta',
    )
    hint = terminal.write('loading...', y='bottom', dim=True)

    # an effect follows the terminal's clock, and without a duration it takes half a
    # second: one call starts it
    @terminal.hook(on='key', keys='1')
    def sweep(context: xnano.Context):
        card.fx.sweep_in(color='cyan')

    @terminal.hook(on='key', keys='2')
    def slide(context: xnano.Context):
        card.fx.slide_in(direction='left_to_right')

    # an effect is also a `with` block: it lasts as long as the block, and its duration
    # is only the longest that it can last. The hue shifts while the work is done
    with card.fx.hsl_shift(foreground=(360, 0, 0), duration_milliseconds=60_000):
        terminal.clock.sleep(2)  # your slow work goes here

    hint.text = '1 sweep · 2 slide · q quit'
    terminal.run(stop_on='q')
animations

Widgets

All of ratatui's widgets are in xnano.widgets: BarChart, Block, Calendar, Chart, Figure, Gauge, ItemList, LineGauge, Paragraph, Scrollbar, Sparkline, Table and Tabs. Each one is written like text. See every widget.

import xnano
from xnano.styles import Style
from xnano.widgets import Table, TableCell, TableRow

table = Table(
    [
        ['web', 'up', '41 ms'],
        ['api', 'up', '12 ms'],
        ['db', TableCell('down', style=Style(foreground='red')), '—'],
    ],
    header=TableRow(['service', 'status', 'p95'], style=Style(bold=True)),
)

with xnano.new(width=40, height=6) as canvas:
    canvas.write(table, width='100%', height='100%', border='rounded', title='services')
    print(canvas.render(format='ansi'))
widget-table

Pixel art and images

Pixel art is written as text in your code with xnano.pixel_art(). Pictures are loaded from files with xnano.load_image(). Learn more.

import xnano

# each character is one pixel: the palette names the colors, and `.` is see-through
heart = xnano.pixel_art(
    """
    ..RR...RR..
    .RWWR.RRRR.
    RRWRRRRRRRR
    RRRRRRRRRRR
    .RRRRRRRRR.
    ..RRRRRRR..
    ...RRRRR...
    ....RRR....
    .....R.....
    """,
    'R=#e03040 W=#ffffff',
)

# two pixels fit in one cell, one above the other, so the heart takes 11 by 5 cells
print(xnano.region(heart).render(format='ansi'))
pixel-art

Sound

Notes and melodies are plain values. A live terminal plays them through its speaker, and outside one, xnano.play() plays them through your computer's sound output. Learn more.

import xnano

scale = ['C4', 'D4', 'E4', 'G4', 'A4']
chord = xnano.Note(('C4', 'E4', 'G4'), beats=2, instrument='electric_piano')

with xnano.open(height=2) as terminal:
    terminal.write('press 1-5 for a note, space for a chord')
    playing = terminal.write('', y=1, foreground='cyan')

    @terminal.hook(on='key')
    def play_note(context: xnano.Context):
        key = context.keyboard.key
        if key in ('1', '2', '3', '4', '5'):
            pitch = scale[int(key) - 1]
            playing.text = f'♪ {pitch}'
            note = xnano.Note(pitch, beats=0.5)
        elif key == 'space':
            playing.text = '♪ C4 E4 G4'
            note = chord
        else:
            return
        # a computer without a sound output device (over SSH, for example) only shows it
        if context.speaker.is_available:
            context.speaker.play(note)

    # a melody can also be written as text: a pitch, and its length in beats after a `:`
    if terminal.speaker.is_available:
        terminal.speaker.play('C4 E4 G4:2', instrument='piano')
    terminal.run(stop_on='q')
speaker

More

  • Keyboard and mouse: held keys, bindings such as 'ctrl+s', drags, scrolls and pasted text. Hooks & Input.
  • The clock: positions that follow the time, timers, a tempo in bpm and pausing. Time & Effects.
  • The microphone: the level of the sound coming in. Sound.
  • Models: streaming text and decisions from a language model, in xnano.ai.

Examples

examples/ holds complete programs to read and run:

Program What it shows
01_rhythm_circles.py to 04_rhythm_lanes.py Four rhythm games, with pixel art and sound.
05_dashboard.py A service dashboard that updates every second.
06_form.py A form with three steps, each one a run that enter ends.
07_file_picker.py A list of files to move through and open.
08_log_viewer.py A log that follows new lines, scrolls back and filters by level.
09_reader.py Markdown laid out on the terminal, in a theme that you choose.
python examples/05_dashboard.py

rich and textual users

xnano works with rich and textual without an adapter. A canvas is a rich renderable, so rich.print(), a rich Panel and a textual Static show it as it is. In the other direction, xnano.from_rich() writes a rich renderable, or rich markup, on a canvas.

This application has all three on one screen. rich makes the table, xnano puts it on a canvas beside a gauge that follows the clock, and textual shows the canvas between its own header and footer:

import xnano
from rich.table import Table
from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, Static
from xnano.widgets import Gauge


# rich: any renderable, such as this table with rich markup in its cells
def services() -> Table:
    table = Table('service', 'status')
    table.add_row('web', '[green]● up[/green]')
    table.add_row('db', '[yellow]▲ slow[/yellow]')
    return table


# xnano: a canvas holds the rich table beside a gauge that follows the canvas's clock
def dashboard() -> xnano.Canvas:
    canvas = xnano.new(width=50, height=6)
    canvas.write(xnano.from_rich(services()))
    check = Gauge(canvas.clock % 5 / 5, label='next check')
    canvas.write(check, x=24, y=1, width=26, height=3, border='rounded')
    return canvas


# textual: a `Static` shows the canvas as it is, between a header and a footer
class Services(App):
    TITLE = 'services'
    BINDINGS = [('q', 'quit', 'Quit')]

    def compose(self) -> ComposeResult:
        self.canvas = dashboard()
        yield Header()
        yield Static(self.canvas)
        yield Footer()

    def on_mount(self) -> None:
        # textual keeps the time: it moves the xnano clock and shows the canvas again
        self.set_interval(0.1, self.tick)

    def tick(self) -> None:
        self.canvas.clock.step(delta_seconds=0.1)
        self.query_one(Static).update(self.canvas)


if __name__ == '__main__':
    Services().run()
textual

The same canvas prints with rich.print(dashboard()). Make a canvas for textual outside a with block, so it stays open: textual draws the Static after it is made. To write text that has ANSI color codes, such as the output of a command, use StyledText.from_ansi().

Learn More

xnano 2 is a rewrite, and it does not run code written for version 1. The documentation of the original grid and field API is in the v1 branch.

xnano is released under the MIT License.

Metadata

Release files for xnano 2.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xnano 2.3.0
File Size Uploaded Provenance Actions
xnano-2.3.0.tar.gz 1.9 MB Without provenance Details for xnano-2.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xnano 2.3.0
File Interpreter ABI Platform Actions
xnano-2.3.0-py3-none-any.whl Python 3 none any Details for xnano-2.3.0-py3-none-any.whl

Total release size: 2.8 MB

Release files / xnano-2.3.0.tar.gz

Download URL xnano-2.3.0.tar.gz
Size 1.9 MB
Tags Source
SHA-256 checksum
How to use checksums
a4a57163645815cc844715c9ad4b6c68ff5923b7e33c0579295b469fb31bab8e
BLAKE2b-256 checksum
How to use checksums
9a6a20817570cd83a26e9167d38c9e3438fa1a1ce9df1390119d4f65af664cb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / xnano-2.3.0-py3-none-any.whl

Download URL xnano-2.3.0-py3-none-any.whl
Size 877.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
133440498c422615f4e2e576656799249ad67acd800828053597ce18992e6d3d
BLAKE2b-256 checksum
How to use checksums
9a8555951812cda95d8220cfd7f39aa8581cc9f8423ed5f44a65d1f535786225
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for xnano 2.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.3.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page