or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-pexpect

Pure Python module for spawning child applications and controlling them automatically with expect-like functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pexpect@4.9.x

To install, run

npx @tessl/cli install tessl/pypi-pexpect@4.9.0

0

# Pexpect

1

2

A pure Python module for spawning child applications and controlling them automatically. Pexpect provides expect-like functionality for automating interactive applications such as ssh, ftp, passwd, telnet, and more. It enables programmatic control of interactive console applications as if a human were typing commands.

3

4

## Package Information

5

6

- **Package Name**: pexpect

7

- **Language**: Python

8

- **Installation**: `pip install pexpect`

9

- **Requirements**: Python 2.7 or 3.x, ptyprocess>=0.5

10

11

## Core Imports

12

13

```python

14

import pexpect

15

```

16

17

Common imports for specific functionality:

18

19

```python

20

from pexpect import spawn, run, EOF, TIMEOUT, ExceptionPexpect

21

from pexpect.pxssh import pxssh

22

from pexpect.popen_spawn import PopenSpawn

23

from pexpect.fdpexpect import fdspawn

24

from pexpect.socket_pexpect import SocketSpawn

25

from pexpect.replwrap import REPLWrapper

26

```

27

28

## Basic Usage

29

30

```python

31

import pexpect

32

33

# Simple command execution with run()

34

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

35

print(output.decode())

36

37

# Interactive process control with spawn

38

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

39

child.expect('Password:')

40

child.sendline('mypassword')

41

child.expect('$ ')

42

child.sendline('ls')

43

child.expect('$ ')

44

print(child.before.decode())

45

child.close()

46

47

# Context manager support

48

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

49

child.expect('Name:')

50

child.sendline('anonymous')

51

child.expect('ftp>')

52

child.sendline('quit')

53

```

54

55

## Architecture

56

57

Pexpect is built around several core concepts:

58

59

- **spawn**: Main class for creating and controlling child processes using pseudo-terminals (PTY)

60

- **SpawnBase**: Abstract base class providing common functionality for all spawn implementations

61

- **Expecter**: Pattern matching engine that searches for text patterns in child output

62

- **Searchers**: String and regex pattern matching classes for the expect system

63

- **Alternative Spawn Classes**: PopenSpawn (subprocess-based), fdspawn (file descriptor), SocketSpawn (sockets), pxssh (SSH)

64

65

The library provides both high-level functions for simple tasks (run()) and powerful classes for complex interactive automation scenarios.

66

67

**Note**: The `screen` and `ANSI` modules are deprecated. For terminal screen emulation, the maintainers recommend using the `pyte` library instead.

68

69

## Capabilities

70

71

### Process Spawning and Control

72

73

Core functionality for spawning and controlling child processes using pseudo-terminals. Includes the main spawn class and high-level run function for command execution.

74

75

```python { .api }

76

class spawn:

77

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

78

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

79

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

80

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

81

use_poll=False): ...

82

83

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

84

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

85

```

86

87

[Process Control](./process-control.md)

88

89

### Pattern Matching and Expect Operations

90

91

Powerful pattern matching system for waiting for expected output from child processes. Supports both string and regular expression patterns with timeout handling.

92

93

```python { .api }

94

def expect(self, pattern, timeout=-1, searchwindowsize=-1): ...

95

def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1): ...

96

def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1): ...

97

98

class searcher_string:

99

def __init__(self, string, index): ...

100

101

class searcher_re:

102

def __init__(self, pattern, index): ...

103

```

104

105

[Pattern Matching](./pattern-matching.md)

106

107

### SSH Automation

108

109

Specialized SSH connection wrapper that extends spawn with SSH-specific functionality including automatic login, logout, and shell prompt handling.

110

111

```python { .api }

112

class pxssh(spawn):

113

def login(self, server, username, password=None, terminal_type='ansi',

114

original_prompt=r"[#$]", login_timeout=10, port=None,

115

auto_prompt_reset=True, ssh_key=None, quiet=True,

116

sync_multiplier=1, check_local_ip=True, password_regex=None,

117

ssh_tunnels=None, spawn_local_ssh=True, sync_original_prompt=True,

118

ssh_config=None, cmd="ssh"): ...

119

120

def logout(self): ...

121

def prompt(self, timeout=-1): ...

122

```

123

124

[SSH Operations](./ssh-operations.md)

125

126

### Alternative Process Control

127

128

Alternative spawn implementations for different communication mechanisms including subprocess-based spawning, file descriptor control, and socket communication.

129

130

```python { .api }

131

class PopenSpawn(SpawnBase):

132

def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,

133

logfile=None, cwd=None, env=None, encoding=None,

134

codec_errors='strict', preexec_fn=None): ...

135

136

class fdspawn(SpawnBase):

137

def __init__(self, fd, args=None, timeout=30, maxread=2000,

138

searchwindowsize=None, logfile=None, encoding=None,

139

codec_errors='strict'): ...

140

141

class SocketSpawn(SpawnBase):

142

def __init__(self, socket, args=None, timeout=30, maxread=2000,

143

searchwindowsize=None, logfile=None, encoding=None,

144

codec_errors='strict'): ...

145

```

146

147

[Alternative Spawning](./alternative-spawning.md)

148

149

### REPL and Shell Automation

150

151

Tools for automating read-eval-print loops and interactive shells with customizable prompts and command execution.

152

153

```python { .api }

154

class REPLWrapper:

155

def __init__(self, cmd_or_spawn, orig_prompt, prompt_change=None,

156

new_prompt=None, extra_init_cmd=""): ...

157

158

def run_command(self, command, timeout=-1, async_=False): ...

159

```

160

161

[REPL Automation](./repl-automation.md)

162

163

### Utilities and Helpers

164

165

Utility functions for common tasks including executable finding, command line parsing, and file system operations.

166

167

```python { .api }

168

def which(filename, env=None): ...

169

def split_command_line(command_line): ...

170

def is_executable_file(path): ...

171

```

172

173

[Utilities](./utilities.md)

174

175

## Module Constants

176

177

Important constants available in the pexpect module:

178

179

```python { .api }

180

# Special pattern types for expect operations

181

EOF: Exception # Matches end-of-file condition

182

TIMEOUT: Exception # Matches timeout condition

183

184

# Version information

185

__version__: str # Current version string

186

__revision__: str # Revision information

187

```

188

189

## Exception Handling

190

191

```python { .api }

192

class ExceptionPexpect(Exception):

193

def __init__(self, value): ...

194

def get_trace(self): ...

195

196

class EOF(ExceptionPexpect):

197

"""Raised when EOF is read from a child. Usually means the child has exited."""

198

199

class TIMEOUT(ExceptionPexpect):

200

"""Raised when a read time exceeds the timeout."""

201

202

class ExceptionPxssh(ExceptionPexpect):

203

"""Raised for pxssh exceptions."""

204

205

# Additional pxssh-specific exceptions available in pexpect.pxssh module

206

# from pexpect.pxssh import ExceptionPxssh

207

```

208

209

Common exception handling patterns:

210

211

```python

212

import pexpect

213

214

try:

215

child = pexpect.spawn('some_command')

216

child.expect('expected_pattern', timeout=10)

217

except pexpect.TIMEOUT:

218

print('Timeout waiting for pattern')

219

except pexpect.EOF:

220

print('Child process ended unexpectedly')

221

except pexpect.ExceptionPexpect as e:

222

print(f'Pexpect error: {e}')

223

```