0
# xonsh
1
2
## Overview
3
4
Xonsh (pronounced "conch") is a Python-powered shell that combines the best of shell functionality with Python scripting capabilities. It provides a superset of Python syntax with shell primitives, enabling seamless integration between Python code and shell commands in a single interactive session. Xonsh supports cross-platform command execution, extensive customization through xontribs (extensions), sophisticated tab completion, and rich environment management.
5
6
## Package Information
7
8
- **Name**: xonsh
9
- **Type**: Shell/Interactive Environment
10
- **Language**: Python
11
- **Version**: 0.19.9
12
- **License**: BSD 2-Clause License
13
- **Installation**: `pip install xonsh`
14
15
### Dependencies
16
- **Python**: >=3.9
17
- **Optional**: prompt-toolkit (for enhanced shell interface)
18
19
## Core Imports
20
21
```python { .api }
22
# Basic xonsh imports
23
from xonsh.built_ins import XSH # Main xonsh singleton
24
from xonsh.shell import Shell # Shell interface
25
from xonsh.execer import Execer # Code execution engine
26
27
# Environment and configuration
28
from xonsh.environ import Env # Environment management
29
from xonsh.built_ins import XSH # Access to aliases via XSH.aliases
30
31
# API modules for pure Python usage
32
from xonsh.api import subprocess # Subprocess wrappers
33
from xonsh.api import os # OS utilities
34
35
# Completion system
36
from xonsh.completer import Completer
37
from xonsh.completers.tools import RichCompletion, Completion
38
39
# Xontribs (extensions)
40
from xonsh.xontribs import xontribs_load, get_xontribs
41
```
42
43
## Basic Usage
44
45
### Starting Xonsh Shell
46
```python { .api }
47
# Start xonsh shell programmatically
48
from xonsh.main import main
49
main()
50
51
# Or execute xonsh code
52
from xonsh.built_ins import XSH
53
XSH.execer.eval('ls -la')
54
```
55
56
### Environment Access
57
```python { .api }
58
from xonsh.built_ins import XSH
59
60
# Access environment variables
61
env = XSH.env
62
print(env['PATH'])
63
env['MY_VAR'] = 'value'
64
65
# Environment swapping
66
with env.swap(DEBUG=True):
67
# Temporary environment changes
68
pass
69
```
70
71
### Subprocess Execution
72
```python { .api }
73
from xonsh.api.subprocess import run, check_output
74
75
# Run commands with xonsh syntax
76
result = run(['ls', '-la'])
77
output = check_output(['echo', 'hello world'])
78
79
# Captured subprocess execution
80
from xonsh.built_ins import subproc_captured_stdout
81
stdout = subproc_captured_stdout(['ls', '-la'])
82
```
83
84
## Architecture
85
86
Xonsh is built around several key components:
87
88
### Core Components
89
- **XonshSession (XSH)**: Central singleton managing all xonsh state
90
- **Execer**: Parses and executes xonsh code (Python + shell syntax)
91
- **Shell**: Interactive shell interface with various backends
92
- **Environment (Env)**: Enhanced environment variable management
93
- **Completer**: Tab completion system with pluggable completers
94
95
### Key Subsystems
96
- **Parsers**: Handle xonsh syntax parsing and AST transformation
97
- **Procs**: Process and pipeline management
98
- **History**: Command history storage and retrieval
99
- **Aliases**: Command aliasing system
100
- **Xontribs**: Extension/plugin system
101
- **Completers**: Modular completion providers
102
103
## Capabilities
104
105
### [Shell Interface](./shell-interface.md)
106
Core shell functionality including command execution, pipeline management, and interactive features.
107
108
```python { .api }
109
from xonsh.shell import Shell
110
111
# Create shell instance
112
shell = Shell()
113
shell.cmdloop() # Start interactive loop
114
115
# Execute single command
116
shell.default("ls -la")
117
```
118
119
### [Built-ins API](./builtins-api.md)
120
Built-in functions, the XSH singleton, and core xonsh utilities.
121
122
```python { .api }
123
from xonsh.built_ins import XSH, helper, globpath
124
125
# Access main xonsh session
126
session = XSH
127
execer = XSH.execer
128
env = XSH.env
129
history = XSH.history
130
131
# Built-in functions
132
help_info = helper(list) # Get help for objects
133
files = globpath("*.py") # Glob file patterns
134
```
135
136
### [Scripting](./scripting.md)
137
Python integration, code execution, and subprocess handling.
138
139
```python { .api }
140
from xonsh.execer import Execer
141
142
# Execute xonsh code
143
execer = Execer()
144
result = execer.eval("ls | wc -l", ctx={})
145
execer.exec("print('Hello from xonsh')", ctx={})
146
```
147
148
### [Completion](./completion.md)
149
Tab completion system with extensible completers.
150
151
```python { .api }
152
from xonsh.completer import Completer
153
from xonsh.completers.tools import RichCompletion
154
155
# Create completer
156
completer = Completer()
157
completions = completer.complete("gi", "git status", 0, 2)
158
159
# Rich completions
160
rich_comp = RichCompletion("status", description="Show working tree status")
161
```
162
163
### [Configuration](./configuration.md)
164
Environment variables, aliases, and xontrib management.
165
166
```python { .api }
167
from xonsh.environ import Env
168
from xonsh.aliases import FuncAlias
169
from xonsh.xontribs import xontribs_load
170
171
# Environment configuration
172
env = Env()
173
env['XONSH_SHOW_TRACEBACK'] = True
174
175
# Create function alias
176
def my_func():
177
return "Hello world"
178
alias = FuncAlias("hello", my_func)
179
180
# Load xontrib
181
xontribs_load(['vox']) # Virtual environment management
182
```
183
184
### [Directory Management](./directory-management.md)
185
Directory navigation, stack operations, and path utilities.
186
187
```python { .api }
188
from xonsh.dirstack import cd, pushd_fn, popd_fn, dirs_fn, with_pushd
189
190
# Directory navigation
191
cd(['/tmp']) # Change directory
192
pushd_fn(['/var']) # Push directory to stack
193
popd_fn([]) # Pop from stack
194
195
# Context manager for temporary directory changes
196
with with_pushd('/tmp'):
197
# Work in /tmp
198
pass
199
```
200
201
### [Aliases](./aliases.md)
202
Command aliases, function shortcuts, and command transformations.
203
204
```python { .api }
205
from xonsh.aliases import Aliases, FuncAlias, ExecAlias
206
from xonsh.built_ins import XSH
207
208
# Access global aliases
209
aliases = XSH.aliases
210
211
# Function alias
212
def greet(args, stdin=None):
213
name = args[0] if args else "World"
214
print(f"Hello, {name}!")
215
216
aliases['greet'] = FuncAlias(greet)
217
218
# Executable alias
219
aliases['ll'] = ExecAlias('ls -la')
220
```
221
222
### [Events](./events.md)
223
Event system for shell lifecycle hooks and customization.
224
225
```python { .api }
226
from xonsh.events import events
227
228
# Register event handlers
229
@events.on_precommand
230
def before_command(cmd: str):
231
"""Called before command execution."""
232
print(f"About to run: {cmd}")
233
234
@events.on_postcommand
235
def after_command(cmd: str, rtn: int, out: str, ts: list):
236
"""Called after command execution."""
237
if rtn != 0:
238
print(f"Command failed with code {rtn}")
239
```
240
241
### [API Package](./api-package.md)
242
Pure Python API for external tools and libraries.
243
244
```python { .api }
245
from xonsh.api.subprocess import run, check_call, check_output
246
from xonsh.api.os import rmtree, indir
247
248
# Enhanced subprocess operations
249
result = run(['ls', '-la'], cwd='/tmp')
250
output = check_output(['git', 'rev-parse', 'HEAD'])
251
252
# Cross-platform OS utilities
253
with indir('/tmp'):
254
# Work in temporary directory
255
rmtree('old_directory', force=True)
256
```
257
258
## Event System
259
260
Xonsh provides an extensive event system for customization:
261
262
```python { .api }
263
from xonsh.events import events
264
265
# Register event handlers
266
@events.on_precommand
267
def before_command(cmd):
268
print(f"About to run: {cmd}")
269
270
@events.on_postcommand
271
def after_command(cmd, rtn, out, ts):
272
print(f"Command '{cmd}' returned {rtn}")
273
```
274
275
## Advanced Features
276
277
### Custom Completers
278
```python { .api }
279
from xonsh.completers.tools import contextual_completer
280
281
@contextual_completer
282
def my_completer(context):
283
"""Custom completer function"""
284
if context.command and context.command.arg_index == 1:
285
return ['option1', 'option2', 'option3']
286
return set()
287
```
288
289
### Process Management
290
```python { .api }
291
from xonsh.procs.jobs import jobs, fg, bg
292
from xonsh.procs.pipelines import Pipeline
293
294
# Job control
295
job_list = jobs() # List active jobs
296
fg(1) # Foreground job 1
297
bg(1) # Background job 1
298
299
# Pipeline creation
300
pipeline = Pipeline(['ls', '-la'], ['grep', 'py'])
301
```
302
303
This documentation provides comprehensive coverage of xonsh's capabilities, enabling AI agents to effectively use xonsh for shell automation, Python scripting integration, and interactive computing tasks.