or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-parsing.mdcollections.mdconfiguration.mdindex.mdsubprocess-runners.mdtask-execution.mdwatchers.md

index.mddocs/

0

# Invoke

1

2

Invoke is a Python library for managing shell-oriented subprocesses and organizing executable Python code into CLI-invokable tasks. It provides a powerful framework for creating command-line interfaces, executing shell commands with proper error handling and output capture, organizing tasks into collections, and managing configuration through multiple sources.

3

4

## Package Information

5

6

- **Package Name**: invoke

7

- **Language**: Python

8

- **Installation**: `pip install invoke`

9

10

## Core Imports

11

12

```python

13

import invoke

14

```

15

16

Common imports for basic usage:

17

18

```python

19

from invoke import task, run, Context, Collection

20

```

21

22

Full import for comprehensive functionality:

23

24

```python

25

from invoke import (

26

# Core execution

27

run, sudo, Context, MockContext,

28

# Task management

29

task, call, Task, Call, Collection,

30

# Configuration

31

Config,

32

# CLI and program management

33

Program, Executor,

34

# Subprocess execution

35

Runner, Local, Result, Promise, Failure,

36

# CLI parsing

37

Parser, Argument, ParserContext, ParseResult,

38

# Collection loading

39

FilesystemLoader,

40

# Stream watchers

41

StreamWatcher, Responder, FailingResponder,

42

# Utilities

43

pty_size,

44

# Exceptions

45

Exit, ParseError, UnexpectedExit, CollectionNotFound,

46

CommandTimedOut, AuthFailure, WatcherError

47

)

48

```

49

50

## Basic Usage

51

52

### Simple Command Execution

53

54

```python

55

from invoke import run

56

57

# Run a simple command

58

result = run("ls -la")

59

print("Return code:", result.return_code)

60

print("Output:", result.stdout)

61

62

# Run with sudo

63

result = run("sudo service nginx restart", pty=True)

64

```

65

66

### Task Definition and Execution

67

68

```python

69

from invoke import task, Collection

70

71

@task

72

def hello(ctx, name="World"):

73

"""Say hello to someone."""

74

print(f"Hello {name}!")

75

76

@task

77

def deploy(ctx, env="staging"):

78

"""Deploy application to environment."""

79

ctx.run(f"git push {env} main")

80

ctx.run(f"ssh {env} 'systemctl restart app'")

81

82

# Create collection and run

83

ns = Collection(hello, deploy)

84

```

85

86

### Context-based Execution

87

88

```python

89

from invoke import Context

90

91

# Create context for command execution

92

ctx = Context()

93

94

# Execute commands through context

95

result = ctx.run("echo 'Hello World'", hide=True)

96

print(result.stdout)

97

98

# Change working directory

99

with ctx.cd('/tmp'):

100

ctx.run("pwd") # Shows /tmp

101

102

# Use command prefixes

103

with ctx.prefix('source venv/bin/activate'):

104

ctx.run("python --version")

105

```

106

107

## Architecture

108

109

Invoke's architecture is built around several key concepts:

110

111

- **Tasks**: Decorated Python functions that can be invoked from CLI

112

- **Context**: Execution environment providing subprocess management and configuration

113

- **Collections**: Hierarchical task organization and namespacing

114

- **Runners**: Pluggable command execution strategies (Local, SSH, etc.)

115

- **Configuration**: Multi-source config system (files, env vars, CLI args)

116

- **Watchers**: Stream processors for interactive subprocess communication

117

118

## Capabilities

119

120

### Task Definition and Execution

121

122

Core functionality for defining Python functions as invokable tasks, with argument parsing, help generation, and execution management.

123

124

```python { .api }

125

def task(*args, **kwargs): ...

126

def call(task, *args, **kwargs) -> Call: ...

127

128

class Task:

129

def __init__(self, body, name=None, aliases=None, positional=None, optional=None, default=False, auto_shortflags=True, help=None, pre=None, post=None, iterable=None, incrementable=None): ...

130

131

class Call:

132

def __init__(self, task, args=None, kwargs=None): ...

133

def make_context(self, config): ...

134

```

135

136

[Task Definition and Execution](./task-execution.md)

137

138

### Subprocess Command Execution

139

140

Command execution through contexts with support for various runners, output capture, error handling, and interactive features.

141

142

```python { .api }

143

def run(command: str, **kwargs) -> Result: ...

144

def sudo(command: str, **kwargs) -> Result: ...

145

146

class Context:

147

def run(self, command, **kwargs): ...

148

def sudo(self, command, **kwargs): ...

149

def cd(self, path): ...

150

def prefix(self, command): ...

151

152

class Result:

153

return_code: int

154

stdout: str

155

stderr: str

156

ok: bool

157

failed: bool

158

```

159

160

[Subprocess Command Execution](./subprocess-runners.md)

161

162

### Configuration Management

163

164

Multi-source configuration system supporting files, environment variables, and command-line arguments with hierarchical merging.

165

166

```python { .api }

167

class Config:

168

def __init__(self, defaults=None, overrides=None, lazy=False, runtime_path=None, system_prefix=None, user_prefix=None, project_location=None, env_prefix=None, file_prefix=None): ...

169

def load_defaults(self, merge=True): ...

170

def merge(self, *dicts): ...

171

def clone(self, into=None): ...

172

```

173

174

[Configuration Management](./configuration.md)

175

176

### CLI Argument Parsing

177

178

Comprehensive argument parsing system supporting flags, options, positional arguments, and help generation.

179

180

```python { .api }

181

class Parser:

182

def __init__(self, contexts=None, initial=None, ignore_unknown=False): ...

183

def parse_argv(self, argv): ...

184

185

class Argument:

186

def __init__(self, names=None, kind=str, default=None, help=None, positional=False, optional=None, incrementable=False, iterable=False, attr_name=None): ...

187

188

class ParseResult:

189

def __getitem__(self, index): ...

190

def __iter__(self): ...

191

```

192

193

[CLI Argument Parsing](./cli-parsing.md)

194

195

### Task Collections

196

197

Hierarchical organization of tasks into collections with namespace management, auto-discovery, and configuration integration.

198

199

```python { .api }

200

class Collection:

201

def __init__(self, *args, **kwargs): ...

202

def add_task(self, task, name=None, aliases=None, default=None): ...

203

def add_collection(self, coll, name=None): ...

204

@classmethod

205

def from_module(cls, module, name=None, config=None, loaded_from=None, auto_dash_names=True): ...

206

```

207

208

[Task Collections](./collections.md)

209

210

### Stream Watchers

211

212

Interactive subprocess communication through pattern-based responders and stream processors.

213

214

```python { .api }

215

class StreamWatcher:

216

def submit(self, stream): ...

217

218

class Responder(StreamWatcher):

219

def __init__(self, pattern, response, sentinel=None): ...

220

def pattern_matches(self, stream, pattern): ...

221

222

class FailingResponder(Responder):

223

def __init__(self, pattern, response, sentinel=None): ...

224

```

225

226

[Stream Watchers](./watchers.md)

227

228

## Types

229

230

### Core Types

231

232

```python { .api }

233

class Context:

234

config: Config

235

cwd: str

236

237

class MockContext(Context):

238

pass

239

240

class Task:

241

name: str

242

called: bool

243

times_called: int

244

245

class Call:

246

task: Task

247

args: tuple

248

kwargs: dict

249

250

class Collection:

251

task_names: list

252

253

class Config:

254

pass

255

256

class Result:

257

return_code: int

258

stdout: str

259

stderr: str

260

ok: bool

261

failed: bool

262

263

class Promise(Result):

264

pass

265

266

class Failure:

267

result: Result

268

reason: str

269

```

270

271

### Exception Types

272

273

```python { .api }

274

class Exit(SystemExit):

275

code: int

276

277

class ParseError(ValueError):

278

pass

279

280

class CollectionNotFound(ImportError):

281

pass

282

283

class UnexpectedExit(Exception):

284

result: Result

285

286

class CommandTimedOut(Exception):

287

timeout: float

288

289

class AuthFailure(Exception):

290

result: Result

291

292

class WatcherError(Exception):

293

pass

294

295

class ResponseNotAccepted(Exception):

296

pass

297

298

class SubprocessPipeError(Exception):

299

pass

300

301

class ThreadException(Exception):

302

pass

303

304

class PlatformError(OSError):

305

pass

306

307

class AmbiguousEnvVar(Exception):

308

pass

309

310

class UncastableEnvVar(Exception):

311

pass

312

313

class UnknownFileType(Exception):

314

pass

315

316

class UnpicklableConfigMember(Exception):

317

pass

318

```