liveBook · Manning

Cooked mode

As explained in Python Concurrency with asyncio

Cooked mode is a terminal input mode in which the terminal buffers, preprocesses, and echoes user input before delivering it to an application.

Cooked mode is a terminal input mode that buffers, preprocesses, and echoes user input before delivering it to an application. It handles actions such as Enter and CTRL-C outside the application, making ordinary line input convenient but limiting control over screen output. section 8.4 section 8.4.1

The convenience becomes a problem when background coroutines write to standard output while the terminal echoes input. Both operations target the cursor’s current line, creating a race condition that can disrupt the prompt and corrupt the apparent input. section 8.4

Contrast cooked mode with application-controlled terminal input:

  • Cooked mode lets the terminal echo and process input, so readline-style input works with little application code. section 8.4
  • Raw mode sends every keystroke to the application, requiring it to buffer, preprocess, and echo input itself. section 8.4.1
  • Cbreak mode provides raw-style input while retaining terminal interpretation of keys such as CTRL-C. section 8.4.1

Background delay tasks

A delay command reads a number with input(), then starts an asynchronous delay. While the user types 3 and rapidly presses 1, a completion message appears on the same line; pressing Enter may submit only the remaining visible input.

Listing 8.4 Attempting background tasks
import asyncio
from util import delay
 
 
async def main():
    while True:
        delay_time = input('Enter a time to sleep:')
        asyncio.create_task(delay(int(delay_time)))
 
 
asyncio.run(main())

Shows the simple input loop whose cooked-mode behavior becomes unreliable when asynchronous tasks write output concurrently. section 8.4

How Python Concurrency with asyncio covers it

How deep it goes
Defines terminal buffering, preprocessing, and echoing, then contrasts them with raw and cbreak input control.
Examples
Uses an asynchronous delay prompt whose input line is disrupted by completion messages.
What it assumes
Assumes familiarity with terminal input, standard output, readline, and asynchronous coroutines.
What you can do after
Diagnose input corruption caused by terminal echoing during concurrent standard-output writes.
How it connects
Connects cooked mode to standard input, raw mode, cbreak mode, cursors, race conditions, and escape sequences.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.