or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# cmd2

1

2

A powerful tool for building interactive command line applications in Python. cmd2 extends Python's built-in cmd module with a wealth of features to make it quick and easy for developers to build feature-rich and user-friendly interactive command line applications.

3

4

## Package Information

5

6

- **Package Name**: cmd2

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install cmd2`

10

11

## Core Imports

12

13

```python

14

import cmd2

15

```

16

17

For accessing the main Cmd class:

18

19

```python

20

from cmd2 import Cmd

21

```

22

23

Common decorators and utilities:

24

25

```python

26

from cmd2 import with_argparser, with_category, Settable

27

from cmd2 import style, fg, bg # ANSI styling

28

```

29

30

## Basic Usage

31

32

```python

33

import cmd2

34

import argparse

35

36

class MyApp(cmd2.Cmd):

37

"""Example cmd2 application"""

38

39

def __init__(self):

40

super().__init__()

41

42

def do_greet(self, args):

43

"""Say hello to someone"""

44

if args:

45

self.poutput(f"Hello, {args}!")

46

else:

47

self.poutput("Hello!")

48

49

# Using argparse for command parsing

50

parser = argparse.ArgumentParser()

51

parser.add_argument('name', help='Name to greet')

52

parser.add_argument('-s', '--shout', action='store_true', help='Shout the greeting')

53

54

@cmd2.with_argparser(parser)

55

def do_hello(self, args):

56

"""Advanced greeting with argparse"""

57

greeting = f"Hello, {args.name}!"

58

if args.shout:

59

greeting = greeting.upper()

60

self.poutput(greeting)

61

62

if __name__ == '__main__':

63

app = MyApp()

64

app.cmdloop()

65

```

66

67

## Architecture

68

69

cmd2 is built around a main `Cmd` class that extends Python's standard `cmd.Cmd` with powerful additional features:

70

71

- **Command Processing**: Built-in parsing, history, and execution framework

72

- **Argument Parsing**: Integration with argparse for sophisticated command line parsing

73

- **I/O Redirection**: Support for shell-like redirection with `>`, `>>`, and `|`

74

- **Scripting**: Built-in support for command scripts and Python scripts

75

- **Extensibility**: Plugin system and decorators for customization

76

- **Interactive Features**: Tab completion, command history, and multi-line input

77

78

## Capabilities

79

80

### Core Command Framework

81

82

The main Cmd class that applications inherit from to create command-line interfaces.

83

84

```python { .api }

85

class Cmd(cmd.Cmd):

86

"""An easy but powerful framework for writing line-oriented command interpreters."""

87

88

def __init__(

89

self,

90

completekey: str = 'tab',

91

stdin: Optional[TextIO] = None,

92

stdout: Optional[TextIO] = None,

93

*,

94

persistent_history_file: str = '',

95

persistent_history_length: int = 1000,

96

startup_script: str = '',

97

silence_startup_script: bool = False,

98

include_py: bool = False,

99

include_ipy: bool = False,

100

allow_cli_args: bool = True,

101

transcript_files: Optional[List[str]] = None,

102

allow_redirection: bool = True,

103

multiline_commands: Optional[List[str]] = None,

104

terminators: Optional[List[str]] = None,

105

shortcuts: Optional[Dict[str, str]] = None,

106

command_sets: Optional[Iterable[CommandSet]] = None,

107

auto_load_commands: bool = True,

108

) -> None: ...

109

110

def cmdloop(self, intro: Optional[str] = None) -> None:

111

"""Repeatedly issue a prompt, accept input, parse and dispatch the command."""

112

113

def onecmd_plus_hooks(self, line: str) -> bool:

114

"""Execute command and run all hooks."""

115

116

def poutput(self, msg: Any = '', *, end: str = '\n') -> None:

117

"""Print message respecting output redirection."""

118

119

def perror(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None:

120

"""Print error message to stderr with optional styling."""

121

122

def ppaged(self, msg: Any = '', *, end: str = '\n', chop: bool = False) -> None:

123

"""Print message using pager for long output."""

124

```

125

126

### Command Decorators

127

128

Decorators for enhancing command methods with argument parsing and categorization.

129

130

```python { .api }

131

def with_argparser(

132

parser: argparse.ArgumentParser,

133

*,

134

ns_provider: Optional[Callable[..., argparse.Namespace]] = None,

135

preserve_quotes: bool = False,

136

with_unknown_args: bool = False,

137

) -> Callable[[CommandFunc], CommandFunc]:

138

"""Decorator to parse command arguments using argparse.ArgumentParser."""

139

140

def with_argument_list() -> Callable[[CommandFunc], CommandFunc]:

141

"""Decorator to pass arguments as a list rather than a string."""

142

143

def with_category(category: str) -> Callable[[CommandFunc], CommandFunc]:

144

"""Decorator to categorize commands for help display."""

145

146

def as_subcommand_to(

147

command: str,

148

subcommand: str,

149

*,

150

help: Optional[str] = None

151

) -> Callable[[CommandFunc], CommandFunc]:

152

"""Decorator to register a function as a subcommand."""

153

```

154

155

### ANSI Styling

156

157

Functions for adding colors and styles to terminal output.

158

159

```python { .api }

160

def style(

161

text: Any,

162

*,

163

fg: Optional[Union[FgColor, int, str]] = None,

164

bg: Optional[Union[BgColor, int, str]] = None,

165

bold: Optional[bool] = None,

166

dim: Optional[bool] = None,

167

italic: Optional[bool] = None,

168

underline: Optional[bool] = None,

169

strikethrough: Optional[bool] = None,

170

overline: Optional[bool] = None,

171

reverse: Optional[bool] = None,

172

hidden: Optional[bool] = None

173

) -> str:

174

"""Apply ANSI color and style to text."""

175

176

# Color constants

177

class fg:

178

"""Foreground color constants"""

179

BLACK: FgColor

180

RED: FgColor

181

GREEN: FgColor

182

YELLOW: FgColor

183

BLUE: FgColor

184

MAGENTA: FgColor

185

CYAN: FgColor

186

WHITE: FgColor

187

188

class bg:

189

"""Background color constants"""

190

BLACK: BgColor

191

RED: BgColor

192

GREEN: BgColor

193

YELLOW: BgColor

194

BLUE: BgColor

195

MAGENTA: BgColor

196

CYAN: BgColor

197

WHITE: BgColor

198

```

199

200

### Argument Parsing

201

202

Custom argument parser and completion classes extending argparse functionality.

203

204

```python { .api }

205

class Cmd2ArgumentParser(argparse.ArgumentParser):

206

"""Custom ArgumentParser with better error formatting for cmd2."""

207

208

def __init__(

209

self,

210

prog: Optional[str] = None,

211

usage: Optional[str] = None,

212

description: Optional[str] = None,

213

epilog: Optional[str] = None,

214

parents: Sequence[argparse.ArgumentParser] = [],

215

formatter_class: argparse.HelpFormatter = argparse.RawDescriptionHelpFormatter,

216

prefix_chars: str = '-',

217

fromfile_prefix_chars: Optional[str] = None,

218

argument_default: Any = None,

219

conflict_handler: str = 'error',

220

add_help: bool = True,

221

allow_abbrev: bool = True,

222

) -> None: ...

223

224

class CompletionItem:

225

"""Represents a completion item with description."""

226

227

def __init__(self, text: str, description: str = '') -> None: ...

228

229

def set_default_argument_parser(

230

argument_parser_class: Type[argparse.ArgumentParser]

231

) -> None:

232

"""Set the default ArgumentParser class used by cmd2."""

233

```

234

235

### Command Execution Results

236

237

Classes for handling command execution results and statements.

238

239

```python { .api }

240

class CommandResult:

241

"""Contains the result of running a command via app() function."""

242

243

def __init__(

244

self,

245

stdout: str,

246

stderr: str,

247

data: Optional[Any] = None

248

) -> None:

249

self.stdout = stdout

250

self.stderr = stderr

251

self.data = data

252

253

class Statement:

254

"""Represents a parsed command statement."""

255

256

command: str

257

args: str

258

arg_list: List[str]

259

raw: str

260

command_line: str

261

multiline_command: str

262

terminator: str = '\n'

263

suffix: str = ''

264

pipe_out: bool = False

265

output_to: str = ''

266

```

267

268

### Utilities and Settings

269

270

Utility functions and classes for application configuration.

271

272

```python { .api }

273

class Settable:

274

"""A setting which can be changed via the 'set' command."""

275

276

def __init__(

277

self,

278

name: str,

279

val_type: Type,

280

description: str,

281

choices: Optional[Iterable[str]] = None,

282

*,

283

settable_object: Optional[Any] = None,

284

onchange_cb: Optional[Callable[[str, str, str], None]] = None,

285

) -> None: ...

286

287

def categorize(

288

func: Callable,

289

category: str

290

) -> Callable:

291

"""Categorize a command function."""

292

293

class CompletionMode(Enum):

294

"""Enum for tab completion modes."""

295

SINGLE_TAB = "single"

296

DOUBLE_TAB = "double"

297

298

class CommandSet:

299

"""Set of commands that can be installed into a cmd2 application."""

300

301

def __init__(self) -> None: ...

302

```

303

304

### Exception Classes

305

306

Exception types used throughout cmd2.

307

308

```python { .api }

309

class Cmd2ArgparseError(Exception):

310

"""Raised when argparse has an error parsing arguments."""

311

312

class CommandSetRegistrationError(Exception):

313

"""Raised when a CommandSet fails to register."""

314

315

class CompletionError(Exception):

316

"""Raised when tab completion encounters an error."""

317

318

class SkipPostcommandHooks(Exception):

319

"""Raised to skip postcommand hooks."""

320

```

321

322

## Constants

323

324

```python { .api }

325

COMMAND_NAME: str # Current command name attribute

326

DEFAULT_SHORTCUTS: Dict[str, str] # Default single-character shortcuts

327

DEFAULT_ARGUMENT_PARSER: Type[argparse.ArgumentParser] # Default parser class

328

```

329

330

## Types

331

332

```python { .api }

333

from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, TextIO, Type, Union

334

from enum import Enum

335

import argparse

336

337

# Type aliases

338

CommandFunc = Callable[..., Optional[bool]]

339

FgColor = Union[int, str]

340

BgColor = Union[int, str]

341

```