or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-greenlets.mdindex.mdmonkey-patching.mdnetworking.mdpooling.mdqueues.mdservers.mdsynchronization.mdtimeouts.md

index.mddocs/

0

# Gevent

1

2

A coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libev event loop. Gevent enables writing asynchronous, concurrent programs without explicit threading or callbacks, using cooperative lightweight threads called greenlets that yield control during I/O operations.

3

4

## Package Information

5

6

- **Package Name**: gevent

7

- **Language**: Python

8

- **Installation**: `pip install gevent`

9

10

## Core Imports

11

12

```python

13

import gevent

14

```

15

16

For specific functionality:

17

18

```python

19

from gevent import socket, ssl, subprocess

20

from gevent import pool, queue, event, lock

21

from gevent import monkey, select, fileobject

22

from gevent import timeout, hub

23

```

24

25

## Basic Usage

26

27

```python

28

import gevent

29

from gevent import socket, monkey

30

31

# Patch standard library for cooperative behavior

32

monkey.patch_all()

33

34

def server(port):

35

s = socket.socket()

36

s.bind(('', port))

37

s.listen(1000)

38

39

while True:

40

conn, addr = s.accept()

41

gevent.spawn(handle_client, conn)

42

43

def handle_client(conn):

44

try:

45

data = conn.recv(1024)

46

conn.send(b'HTTP/1.1 200 OK\r\n\r\nHello World')

47

finally:

48

conn.close()

49

50

# Start server

51

gevent.spawn(server, 8080).join()

52

```

53

54

## Architecture

55

56

Gevent's architecture is built around several key components:

57

58

- **Greenlets**: Lightweight cooperative threads that yield control during I/O operations

59

- **Event Loop**: Underlying libev/libuv event loop that manages I/O operations

60

- **Hub**: Central coordinator that manages greenlet scheduling and event dispatching

61

- **Monkey Patching**: Mechanism to transparently replace standard library modules with gevent-aware versions

62

- **Synchronization Primitives**: Cooperative equivalents of threading primitives (locks, events, queues)

63

64

This design allows writing synchronous-looking code that runs asynchronously, providing high concurrency without the complexity of traditional async programming.

65

66

## Capabilities

67

68

### Core Greenlet Management

69

70

Fundamental greenlet operations including spawning, waiting, killing, and coordinating multiple greenlets. These form the foundation of gevent's cooperative concurrency model.

71

72

```python { .api }

73

def spawn(function, *args, **kwargs) -> Greenlet: ...

74

def spawn_later(seconds, function, *args, **kwargs) -> Greenlet: ...

75

def spawn_raw(function, *args, **kwargs) -> Greenlet: ...

76

def joinall(greenlets, timeout=None, raise_error=False): ...

77

def killall(greenlets, exception=GreenletExit, block=True, timeout=None): ...

78

def kill(greenlet, exception=GreenletExit, block=True, timeout=None): ...

79

def sleep(seconds=0): ...

80

def idle(priority=0): ...

81

def get_hub() -> Hub: ...

82

def getcurrent() -> Greenlet: ...

83

def iwait(objects, timeout=None, count=None): ...

84

def wait(objects, timeout=None, count=None): ...

85

def fork() -> int: ...

86

def reinit(): ...

87

def signal_handler(signalnum, handler): ...

88

def getswitchinterval() -> float: ...

89

def setswitchinterval(interval: float): ...

90

```

91

92

[Core Greenlets](./core-greenlets.md)

93

94

### Synchronization Primitives

95

96

Thread-safe synchronization objects adapted for cooperative greenlet concurrency, including events, locks, semaphores, and async result containers.

97

98

```python { .api }

99

class Event:

100

def set(self): ...

101

def clear(self): ...

102

def wait(self, timeout=None) -> bool: ...

103

def is_set(self) -> bool: ...

104

105

class AsyncResult:

106

def set(self, value=None): ...

107

def set_exception(self, exception): ...

108

def get(self, block=True, timeout=None): ...

109

```

110

111

[Synchronization](./synchronization.md)

112

113

### Networking and I/O

114

115

Complete networking stack with cooperative sockets, SSL support, and gevent-aware I/O operations that work seamlessly with greenlets.

116

117

```python { .api }

118

def create_connection(address, timeout=None, source_address=None) -> socket: ...

119

def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): ...

120

121

class socket:

122

def connect(self, address): ...

123

def accept(self) -> tuple[socket, tuple]: ...

124

def recv(self, bufsize, flags=0) -> bytes: ...

125

def send(self, data, flags=0) -> int: ...

126

```

127

128

[Networking](./networking.md)

129

130

### Concurrency and Pooling

131

132

Tools for managing groups of greenlets including pools with size limits, groups for coordination, and thread pools for CPU-bound operations.

133

134

```python { .api }

135

class Pool:

136

def __init__(self, size=None, greenlet_class=None): ...

137

def spawn(self, function, *args, **kwargs) -> Greenlet: ...

138

def map(self, func, iterable, maxsize=None): ...

139

def imap(self, func, iterable, maxsize=None): ...

140

141

class Group:

142

def add(self, greenlet): ...

143

def spawn(self, function, *args, **kwargs) -> Greenlet: ...

144

def join(self, timeout=None, raise_error=False): ...

145

```

146

147

[Pooling](./pooling.md)

148

149

### Queues and Communication

150

151

Message passing and data structures for greenlet communication including FIFO, LIFO, and priority queues with cooperative blocking behavior.

152

153

```python { .api }

154

class Queue:

155

def __init__(self, maxsize=None, items=None, unfinished_tasks=None): ...

156

def put(self, item, block=True, timeout=None): ...

157

def get(self, block=True, timeout=None): ...

158

def task_done(self): ...

159

def join(self, timeout=None): ...

160

161

class PriorityQueue: ...

162

class LifoQueue: ...

163

```

164

165

[Queues](./queues.md)

166

167

### Servers and HTTP

168

169

High-performance server implementations including generic TCP/UDP servers and a complete WSGI HTTP server for web applications.

170

171

```python { .api }

172

class StreamServer:

173

def __init__(self, listener, handle=None, backlog=None, spawn='default', **ssl_args): ...

174

def serve_forever(self, stop_timeout=None): ...

175

def start(self): ...

176

def stop(self, timeout=None): ...

177

178

class WSGIServer:

179

def __init__(self, listener, application, **kwargs): ...

180

def serve_forever(self): ...

181

```

182

183

[Servers](./servers.md)

184

185

### Timeouts and Control Flow

186

187

Timeout management and control flow utilities including context managers for timeouts and cooperative equivalents of standard library functions.

188

189

```python { .api }

190

class Timeout:

191

def __init__(self, seconds=None, exception=None, ref=True, priority=-1): ...

192

def start(self): ...

193

def cancel(self): ...

194

def close(self): ...

195

def __enter__(self): ...

196

def __exit__(self, exc_type, exc_val, exc_tb): ...

197

@property

198

def pending(self) -> bool: ...

199

@property

200

def seconds(self) -> float: ...

201

202

def with_timeout(seconds, function, *args, **kwargs): ...

203

```

204

205

[Timeouts](./timeouts.md)

206

207

### Monkey Patching

208

209

Transparent replacement of standard library modules with gevent-aware equivalents, enabling existing code to work cooperatively without modification.

210

211

```python { .api }

212

def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, subprocess=True, sys=False, aggressive=True, Event=True, builtins=True, signal=True, queue=True, contextvars=True, **kwargs): ...

213

def patch_socket(): ...

214

def patch_ssl(): ...

215

def patch_thread(): ...

216

```

217

218

[Monkey Patching](./monkey-patching.md)

219

220

### Subprocess and System Integration

221

222

Cooperative subprocess execution and system-level integration features that work seamlessly with gevent's event loop.

223

224

```python { .api }

225

class Popen:

226

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

227

def communicate(self, input=None, timeout=None) -> tuple[bytes, bytes]: ...

228

def wait(self, timeout=None) -> int: ...

229

def poll(self) -> int: ...

230

def kill(self): ...

231

def terminate(self): ...

232

233

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

234

def check_call(args, **kwargs) -> int: ...

235

def check_output(args, **kwargs) -> bytes: ...

236

```

237

238

### File Objects and Select

239

240

Cooperative file objects and select-style operations that integrate with gevent's event loop for non-blocking I/O.

241

242

```python { .api }

243

class FileObjectThread:

244

def __init__(self, fobj, mode='rb', bufsize=-1, close=True): ...

245

def read(self, size=-1) -> bytes: ...

246

def write(self, data: bytes) -> int: ...

247

def flush(self): ...

248

def close(self): ...

249

250

def select(rlist, wlist, xlist, timeout=None): ...

251

```

252

253

## Global Types

254

255

```python { .api }

256

class Greenlet:

257

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

258

def start(self): ...

259

def start_later(self, seconds): ...

260

def join(self, timeout=None): ...

261

def kill(self, exception=GreenletExit, block=True, timeout=None): ...

262

def get(self, block=True, timeout=None): ...

263

def throw(self, *args): ...

264

def ready(self) -> bool: ...

265

def successful(self) -> bool: ...

266

def rawlink(self, callback): ...

267

def link(self, callback): ...

268

def unlink(self, callback): ...

269

def unlink_all(self): ...

270

def link_value(self, callback): ...

271

def link_exception(self, callback): ...

272

@classmethod

273

def spawn(cls, *args, **kwargs) -> 'Greenlet': ...

274

@classmethod

275

def spawn_later(cls, seconds, *args, **kwargs) -> 'Greenlet': ...

276

@staticmethod

277

def add_spawn_callback(callback): ...

278

@staticmethod

279

def remove_spawn_callback(callback): ...

280

@property

281

def started(self) -> bool: ...

282

@property

283

def dead(self) -> bool: ...

284

@property

285

def name(self) -> str: ...

286

@property

287

def minimal_ident(self) -> int: ...

288

@property

289

def exception(self): ...

290

@property

291

def exc_info(self): ...

292

293

class GreenletExit(BaseException): ...

294

295

class Hub:

296

def switch(self): ...

297

def run(self): ...

298

def stop(self): ...

299

def destroy(self): ...

300

def join(self, timeout=None): ...

301

@property

302

def loop(self): ...

303

```