or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aliases.mdapi-package.mdbuiltins-api.mdcompletion.mdconfiguration.mddirectory-management.mdevents.mdindex.mdscripting.mdshell-interface.md

builtins-api.mddocs/

0

# Built-ins API

1

2

## Overview

3

4

Xonsh's built-ins provide the core functionality available in all xonsh sessions. The central component is the XSH singleton (XonshSession), which manages all session state including the executer, environment, shell, and history. Built-in functions provide utilities for path manipulation, subprocess execution, and interactive help.

5

6

## XonshSession (XSH)

7

8

### Core Session Object

9

```python { .api }

10

from xonsh.built_ins import XSH, XonshSession

11

12

class XonshSession:

13

"""Central session object managing all xonsh components."""

14

15

def __init__(self):

16

"""Initialize xonsh session.

17

18

Attributes

19

----------

20

execer : Execer

21

Code execution engine

22

ctx : dict

23

Execution context/namespace

24

builtins_loaded : bool

25

Whether built-ins have been loaded

26

history : History

27

Command history manager

28

shell : Shell

29

Interactive shell instance

30

env : Env

31

Environment variable manager

32

exit : int or None

33

Exit code for session termination

34

"""

35

self.execer = None

36

self.ctx = {}

37

self.builtins_loaded = False

38

self.history = None

39

self.shell = None

40

self.env = None

41

self.exit = None

42

43

# Global session singleton

44

XSH: XonshSession # Main xonsh session instance

45

```

46

47

### Session Access Patterns

48

```python { .api }

49

from xonsh.built_ins import XSH

50

51

# Access core components

52

executer = XSH.execer # Code execution

53

environment = XSH.env # Environment variables

54

shell = XSH.shell # Interactive shell

55

history = XSH.history # Command history

56

context = XSH.ctx # Execution namespace

57

58

# Check session state

59

if XSH.builtins_loaded:

60

print("Xonsh session fully initialized")

61

62

# Session termination

63

XSH.exit = 0 # Set exit code

64

```

65

66

## Built-in Functions

67

68

### Help and Inspection

69

```python { .api }

70

from xonsh.built_ins import helper, superhelper

71

72

def helper(obj, name: str = "") -> object:

73

"""Show help for an object and return it.

74

75

Parameters

76

----------

77

obj : object

78

Object to get help for

79

name : str, optional

80

Name to display for the object

81

82

Returns

83

-------

84

object

85

The original object (for chaining)

86

"""

87

88

def superhelper(obj, name: str = "") -> object:

89

"""Show detailed help for an object and return it.

90

91

Parameters

92

----------

93

obj : object

94

Object to get detailed help for

95

name : str, optional

96

Name to display for the object

97

98

Returns

99

-------

100

object

101

The original object (for chaining)

102

"""

103

104

# Usage examples

105

help_result = helper(list) # Show help for list type

106

detailed_help = superhelper(dict) # Show detailed help for dict

107

chained = helper(str.split, "split") # Show help with custom name

108

```

109

110

### Path and File Operations

111

```python { .api }

112

from xonsh.built_ins import globpath, expand_path, pathsearch

113

114

def globpath(pattern: str, ignore_hidden: bool = False,

115

return_empty: bool = False) -> list[str]:

116

"""Glob file paths matching a pattern.

117

118

Parameters

119

----------

120

pattern : str

121

Glob pattern (supports *, ?, [], etc.)

122

ignore_hidden : bool, default False

123

Whether to ignore hidden files

124

return_empty : bool, default False

125

Whether to return empty list if no matches

126

127

Returns

128

-------

129

list[str]

130

List of matching file paths

131

"""

132

133

def expand_path(path: str) -> str:

134

"""Expand user home directory and environment variables.

135

136

Parameters

137

----------

138

path : str

139

Path potentially containing ~ or $VAR

140

141

Returns

142

-------

143

str

144

Expanded absolute path

145

"""

146

147

def pathsearch(func, path: str, pymode: bool = False,

148

ignore_hidden: bool = False) -> list[str]:

149

"""Search for files matching a function criteria.

150

151

Parameters

152

----------

153

func : callable

154

Function to test each path

155

path : str

156

Directory path to search

157

pymode : bool, default False

158

Whether to use Python mode evaluation

159

ignore_hidden : bool, default False

160

Whether to ignore hidden files

161

162

Returns

163

-------

164

list[str]

165

List of matching paths

166

"""

167

168

# Usage examples

169

py_files = globpath("*.py") # Find Python files

170

config_files = globpath("~/.config/*") # Expand home directory

171

home_path = expand_path("~/Documents") # Expand to absolute path

172

executables = pathsearch(lambda p: os.access(p, os.X_OK), "/usr/bin")

173

```

174

175

### Regular Expression Search

176

```python { .api }

177

from xonsh.built_ins import regexsearch, globsearch, reglob

178

179

def regexsearch(func, pattern: str, path: str = ".") -> list[str]:

180

"""Search files using regex pattern.

181

182

Parameters

183

----------

184

func : callable

185

Function to apply to matching content

186

pattern : str

187

Regular expression pattern

188

path : str, default "."

189

Directory to search

190

191

Returns

192

-------

193

list[str]

194

List of matching results

195

"""

196

197

def globsearch(func, pattern: str) -> list[str]:

198

"""Search using glob pattern and apply function.

199

200

Parameters

201

----------

202

func : callable

203

Function to apply to each match

204

pattern : str

205

Glob pattern for file matching

206

207

Returns

208

-------

209

list[str]

210

List of function results

211

"""

212

213

def reglob(path: str, parts: list = None, i: int = None) -> list[str]:

214

"""Regular expression-based globbing.

215

216

Parameters

217

----------

218

path : str

219

Path pattern with regex components

220

parts : list, optional

221

Path components for recursive processing

222

i : int, optional

223

Current part index

224

225

Returns

226

-------

227

list[str]

228

List of matching paths

229

"""

230

231

# Usage examples

232

log_files = globsearch(str, "*.log") # Find log files

233

py_imports = regexsearch(str, r"^import\s+", ".") # Find import statements

234

regex_paths = reglob(r"test_.*\.py") # Regex-based file matching

235

```

236

237

## Subprocess Execution

238

239

### Subprocess Capture Functions

240

```python { .api }

241

from xonsh.built_ins import (subproc_captured_stdout, subproc_captured_inject,

242

subproc_captured_object, subproc_captured_hiddenobject,

243

subproc_uncaptured)

244

245

def subproc_captured_stdout(cmd: list[str]) -> str:

246

"""Execute subprocess and capture stdout as string.

247

248

Parameters

249

----------

250

cmd : list[str]

251

Command and arguments to execute

252

253

Returns

254

-------

255

str

256

Captured stdout content

257

"""

258

259

def subproc_captured_object(cmd: list[str]) -> object:

260

"""Execute subprocess and return process object.

261

262

Parameters

263

----------

264

cmd : list[str]

265

Command and arguments to execute

266

267

Returns

268

-------

269

object

270

Process object with stdout, stderr, returncode

271

"""

272

273

def subproc_captured_hiddenobject(cmd: list[str]) -> object:

274

"""Execute subprocess with hidden output, return process object.

275

276

Parameters

277

----------

278

cmd : list[str]

279

Command and arguments to execute

280

281

Returns

282

-------

283

object

284

Process object (output not displayed)

285

"""

286

287

def subproc_uncaptured(cmd: list[str]) -> None:

288

"""Execute subprocess without capturing output.

289

290

Parameters

291

----------

292

cmd : list[str]

293

Command and arguments to execute

294

"""

295

296

def subproc_captured_inject(cmd: list[str]) -> str:

297

"""Execute subprocess and inject output into current context.

298

299

Parameters

300

----------

301

cmd : list[str]

302

Command and arguments to execute

303

304

Returns

305

-------

306

str

307

Captured output (also injected to context)

308

"""

309

310

# Usage examples

311

output = subproc_captured_stdout(['ls', '-la']) # Get stdout

312

proc = subproc_captured_object(['git', 'status']) # Get process object

313

hidden_proc = subproc_captured_hiddenobject(['make']) # Hidden execution

314

subproc_uncaptured(['vim', 'file.txt']) # Interactive command

315

```

316

317

## Macro System

318

319

### Macro Execution

320

```python { .api }

321

from xonsh.built_ins import call_macro, enter_macro

322

323

def call_macro(name: str, *args, **kwargs) -> object:

324

"""Call a xonsh macro by name.

325

326

Parameters

327

----------

328

name : str

329

Macro name to call

330

*args

331

Positional arguments to macro

332

**kwargs

333

Keyword arguments to macro

334

335

Returns

336

-------

337

object

338

Macro return value

339

"""

340

341

def enter_macro(name: str, *args, **kwargs) -> object:

342

"""Enter a macro context.

343

344

Parameters

345

----------

346

name : str

347

Macro name to enter

348

*args

349

Positional arguments

350

**kwargs

351

Keyword arguments

352

353

Returns

354

-------

355

object

356

Macro context result

357

"""

358

359

# Macro usage examples

360

result = call_macro('my_macro', arg1='value')

361

with enter_macro('context_macro'):

362

# Code executed in macro context

363

pass

364

```

365

366

## Data Type Utilities

367

368

### String and List Processing

369

```python { .api }

370

from xonsh.built_ins import (list_of_strs_or_callables,

371

list_of_list_of_strs_outer_product,

372

path_literal)

373

374

def list_of_strs_or_callables(items) -> list:

375

"""Convert input to list of strings or callables.

376

377

Parameters

378

----------

379

items : various

380

Input to convert to list

381

382

Returns

383

-------

384

list

385

List of strings or callable objects

386

"""

387

388

def list_of_list_of_strs_outer_product(items) -> list[list[str]]:

389

"""Create outer product of string lists.

390

391

Parameters

392

----------

393

items : list[list[str]]

394

List of string lists to combine

395

396

Returns

397

-------

398

list[list[str]]

399

Outer product combinations

400

"""

401

402

def path_literal(path: str) -> str:

403

"""Convert path to literal path string.

404

405

Parameters

406

----------

407

path : str

408

Path to convert

409

410

Returns

411

-------

412

str

413

Literal path string

414

"""

415

416

# Usage examples

417

str_list = list_of_strs_or_callables(['a', 'b', lambda: 'c'])

418

combinations = list_of_list_of_strs_outer_product([['a', 'b'], ['1', '2']])

419

literal_path = path_literal('/path/with spaces')

420

```

421

422

### F-string Field Evaluation

423

```python { .api }

424

from xonsh.built_ins import eval_fstring_field

425

426

def eval_fstring_field(field: str, ctx: dict) -> str:

427

"""Evaluate f-string field in given context.

428

429

Parameters

430

----------

431

field : str

432

F-string field expression

433

ctx : dict

434

Evaluation context

435

436

Returns

437

-------

438

str

439

Evaluated field value

440

"""

441

442

# Usage example

443

context = {'name': 'world', 'x': 42}

444

result = eval_fstring_field('name.upper()', context) # 'WORLD'

445

result = eval_fstring_field('x * 2', context) # '84'

446

```

447

448

## Session Management

449

450

### Session Attributes

451

```python { .api }

452

from xonsh.built_ins import XSH

453

454

# Core session components access

455

executer = XSH.execer # Execer instance

456

environment = XSH.env # Environment manager

457

shell_instance = XSH.shell # Shell interface

458

command_history = XSH.history # History manager

459

460

# Session state

461

context = XSH.ctx # Execution namespace

462

exit_code = XSH.exit # Session exit code

463

loaded = XSH.builtins_loaded # Initialization status

464

465

# Caching systems

466

commands_cache = XSH.commands_cache # Command lookup cache

467

modules_cache = XSH.modules_cache # Python module cache

468

469

# Job management

470

job_manager = XSH.all_jobs # Active job manager

471

472

# Stream handling

473

stdout_uncaptured = XSH.stdout_uncaptured # Uncaptured stdout

474

stderr_uncaptured = XSH.stderr_uncaptured # Uncaptured stderr

475

```

476

477

### Session Lifecycle

478

```python { .api }

479

from xonsh.built_ins import XSH

480

481

# Session initialization check

482

if not XSH.builtins_loaded:

483

print("Session not fully initialized")

484

485

# Graceful session termination

486

def exit_xonsh(code=0):

487

"""Exit xonsh session with code."""

488

XSH.exit = code

489

490

# Session cleanup

491

def cleanup_session():

492

"""Clean up session resources."""

493

if XSH.shell:

494

XSH.shell.reset()

495

if XSH.history:

496

XSH.history.flush()

497

```

498

499

The built-ins API provides the foundation for all xonsh functionality, offering both low-level session management and high-level utility functions for common shell and scripting tasks.