or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

alternative-spawning.mdindex.mdpattern-matching.mdprocess-control.mdrepl-automation.mdssh-operations.mdutilities.md

process-control.mddocs/

0

# Process Spawning and Control

1

2

Core functionality for spawning and controlling child processes using pseudo-terminals. This module provides the fundamental classes and functions for process automation in pexpect.

3

4

## Capabilities

5

6

### Main Spawn Class

7

8

The primary interface for spawning and controlling child processes with pseudo-terminal (PTY) support.

9

10

```python { .api }

11

class spawn(SpawnBase):

12

"""

13

Main class interface for Pexpect. Use this class to start and control child applications.

14

15

Parameters:

16

- command (str): Command to execute, can include arguments

17

- args (list): Command arguments as separate list items

18

- timeout (int): Default timeout in seconds for expect operations

19

- maxread (int): Maximum number of bytes to read at once

20

- searchwindowsize (int): Number of bytes to keep in search window

21

- logfile (file-like): File object to log all I/O

22

- cwd (str): Working directory for child process

23

- env (dict): Environment variables for child process

24

- ignore_sighup (bool): Ignore SIGHUP signal

25

- echo (bool): Enable/disable terminal echo

26

- preexec_fn (callable): Function to call before exec in child

27

- encoding (str): Text encoding for I/O operations

28

- codec_errors (str): How to handle encoding errors

29

- dimensions (tuple): Terminal size as (rows, cols)

30

- use_poll (bool): Use poll() instead of select()

31

"""

32

def __init__(self, command, args=[], timeout=30, maxread=2000,

33

searchwindowsize=None, logfile=None, cwd=None, env=None,

34

ignore_sighup=False, echo=True, preexec_fn=None,

35

encoding=None, codec_errors='strict', dimensions=None,

36

use_poll=False): ...

37

```

38

39

### Process Lifecycle Methods

40

41

```python { .api }

42

def close(self, force=True):

43

"""

44

Close the connection with the child application.

45

46

Parameters:

47

- force (bool): Force termination if child doesn't close gracefully

48

"""

49

50

def terminate(self, force=False):

51

"""

52

Terminate the child process.

53

54

Parameters:

55

- force (bool): Send SIGKILL instead of SIGTERM

56

"""

57

58

def kill(self, sig):

59

"""

60

Send signal to the child process.

61

62

Parameters:

63

- sig (int): Signal number to send

64

"""

65

66

def wait(self):

67

"""

68

Wait for the child process to exit.

69

70

Returns:

71

int: Exit status of child process

72

"""

73

74

def isalive(self):

75

"""

76

Check if child process is still running.

77

78

Returns:

79

bool: True if child is alive, False otherwise

80

"""

81

```

82

83

### Input/Output Methods

84

85

```python { .api }

86

def send(self, s):

87

"""

88

Send string to child process.

89

90

Parameters:

91

- s (str or bytes): Data to send

92

93

Returns:

94

int: Number of bytes written

95

"""

96

97

def sendline(self, s=''):

98

"""

99

Send string followed by line terminator to child.

100

101

Parameters:

102

- s (str): String to send (default: empty string)

103

104

Returns:

105

int: Number of bytes written

106

"""

107

108

def sendcontrol(self, char):

109

"""

110

Send control character to child.

111

112

Parameters:

113

- char (str): Control character (e.g., 'c' for Ctrl-C)

114

115

Returns:

116

int: Number of bytes written

117

"""

118

119

def sendeof(self):

120

"""

121

Send EOF to child process.

122

"""

123

124

def sendintr(self):

125

"""

126

Send interrupt signal (Ctrl-C) to child.

127

"""

128

129

def read_nonblocking(self, size=1, timeout=-1):

130

"""

131

Read data from child without blocking.

132

133

Parameters:

134

- size (int): Maximum bytes to read

135

- timeout (int): Timeout in seconds (-1 for default)

136

137

Returns:

138

bytes: Data read from child

139

140

Raises:

141

- TIMEOUT: If timeout exceeded

142

- EOF: If child has terminated

143

"""

144

145

def write(self, s):

146

"""

147

Write data to child (no return value).

148

149

Parameters:

150

- s (str or bytes): Data to write

151

"""

152

153

def writelines(self, sequence):

154

"""

155

Write sequence of strings to child.

156

157

Parameters:

158

- sequence (iterable): Sequence of strings to write

159

"""

160

161

def read(self, size=-1):

162

"""

163

Read and return up to size bytes from child.

164

165

Parameters:

166

- size (int): Maximum bytes to read (-1 for all available)

167

168

Returns:

169

bytes or str: Data read from child

170

"""

171

172

def readline(self, size=-1):

173

"""

174

Read and return one line from child.

175

176

Parameters:

177

- size (int): Maximum bytes to read (-1 for unlimited)

178

179

Returns:

180

bytes or str: One line from child

181

"""

182

183

def readlines(self, sizehint=-1):

184

"""

185

Read and return list of lines from child.

186

187

Parameters:

188

- sizehint (int): Hint for number of bytes to read

189

190

Returns:

191

list: List of lines from child

192

"""

193

194

def flush(self):

195

"""

196

Flush the write buffers (if applicable).

197

"""

198

199

def fileno(self):

200

"""

201

Return file descriptor number for the child.

202

203

Returns:

204

int: File descriptor number

205

"""

206

```

207

208

### Terminal Control Methods

209

210

```python { .api }

211

def setecho(self, state):

212

"""

213

Enable or disable terminal echo.

214

215

Parameters:

216

- state (bool): True to enable echo, False to disable

217

"""

218

219

def getecho(self):

220

"""

221

Get current terminal echo state.

222

223

Returns:

224

bool: Current echo state

225

"""

226

227

def waitnoecho(self, timeout=-1):

228

"""

229

Wait for terminal echo to be disabled.

230

231

Parameters:

232

- timeout (int): Timeout in seconds

233

234

Returns:

235

bool: True if echo disabled, False on timeout

236

"""

237

238

def getwinsize(self):

239

"""

240

Get terminal window size.

241

242

Returns:

243

tuple: (rows, cols) terminal dimensions

244

"""

245

246

def setwinsize(self, rows, cols):

247

"""

248

Set terminal window size.

249

250

Parameters:

251

- rows (int): Number of rows

252

- cols (int): Number of columns

253

"""

254

255

def isatty(self):

256

"""

257

Check if connected to a TTY.

258

259

Returns:

260

bool: True if connected to TTY

261

"""

262

263

def interact(self, escape_character=chr(29), input_filter=None, output_filter=None):

264

"""

265

Give control of child to user for interactive session.

266

267

Parameters:

268

- escape_character (str): Character to exit interaction (default: Ctrl-])

269

- input_filter (callable): Filter function for user input

270

- output_filter (callable): Filter function for child output

271

"""

272

273

def eof(self):

274

"""

275

Check if EOF exception was ever raised.

276

277

Returns:

278

bool: True if EOF has been encountered

279

"""

280

281

@property

282

def flag_eof(self):

283

"""

284

Boolean flag indicating if EOF has been encountered.

285

286

Returns:

287

bool: Current EOF flag state

288

"""

289

```

290

291

### High-Level Run Function

292

293

Simple function interface for executing commands and capturing output.

294

295

```python { .api }

296

def run(command, timeout=30, withexitstatus=False, events=None,

297

extra_args=None, logfile=None, cwd=None, env=None, **kwargs):

298

"""

299

Execute command and return output.

300

301

Parameters:

302

- command (str): Command to execute

303

- timeout (int): Timeout in seconds

304

- withexitstatus (bool): Return (output, exitstatus) tuple

305

- events (dict/list): Pattern-response mappings for automation

306

- extra_args (list): Additional arguments for spawn

307

- logfile (file-like): File object for logging

308

- cwd (str): Working directory

309

- env (dict): Environment variables

310

- **kwargs: Additional arguments passed to spawn

311

312

Returns:

313

str or tuple: Command output, or (output, exitstatus) if withexitstatus=True

314

"""

315

```

316

317

### Legacy Unicode Wrappers

318

319

```python { .api }

320

def spawnu(command, args=[], timeout=30, maxread=2000, searchwindowsize=None,

321

logfile=None, cwd=None, env=None, ignore_sighup=False, echo=True,

322

preexec_fn=None, encoding='utf-8', codec_errors='strict',

323

dimensions=None, use_poll=False):

324

"""

325

Deprecated: Use spawn with encoding parameter instead.

326

Unicode wrapper for spawn class.

327

"""

328

329

def runu(command, timeout=30, withexitstatus=False, events=None,

330

extra_args=None, logfile=None, cwd=None, env=None, **kwargs):

331

"""

332

Deprecated: Use run with encoding parameter instead.

333

Unicode wrapper for run function.

334

"""

335

```

336

337

## Key Attributes

338

339

All spawn instances provide these important attributes:

340

341

```python { .api }

342

# Process information

343

pid: int # Child process ID

344

child_fd: int # File descriptor for child

345

exitstatus: int # Exit code (None if running)

346

signalstatus: int # Signal that killed process (None if not killed by signal)

347

348

# Pattern matching results

349

before: str # Text before matched pattern

350

after: str # Text that matched pattern

351

match: Match # Regex match object (for regex patterns)

352

match_index: int # Index of matched pattern in pattern list

353

354

# Configuration

355

timeout: int # Current default timeout

356

logfile: file # Main log file

357

logfile_read: file # Log file for read operations

358

logfile_send: file # Log file for send operations

359

```

360

361

## Usage Examples

362

363

### Basic Process Control

364

365

```python

366

import pexpect

367

368

# Spawn a process

369

child = pexpect.spawn('ssh user@server')

370

371

# Check if process is running

372

if child.isalive():

373

print(f"Process {child.pid} is running")

374

375

# Send commands

376

child.sendline('ls -la')

377

child.expect('$ ')

378

379

# Read output

380

output = child.before

381

print(output.decode())

382

383

# Clean shutdown

384

child.sendline('exit')

385

child.close()

386

```

387

388

### Using run() for Simple Commands

389

390

```python

391

import pexpect

392

393

# Simple command execution

394

output = pexpect.run('ls -la /tmp')

395

print(output.decode())

396

397

# Get exit status

398

output, exitstatus = pexpect.run('ls /nonexistent', withexitstatus=True)

399

print(f"Exit status: {exitstatus}")

400

401

# Automated interaction

402

events = {

403

'Password:': 'mypassword\n',

404

'Are you sure': 'yes\n'

405

}

406

output = pexpect.run('ssh user@server', events=events)

407

```

408

409

### Context Manager Usage

410

411

```python

412

import pexpect

413

414

# Automatic cleanup with context manager

415

with pexpect.spawn('ftp ftp.example.com') as child:

416

child.expect('Name:')

417

child.sendline('anonymous')

418

child.expect('Password:')

419

child.sendline('user@example.com')

420

child.expect('ftp>')

421

child.sendline('quit')

422

# Child is automatically closed

423

```