import sys

sys.stdin and sys.stdout

sys.stdin and sys.stdout are useful when creating an interactive session. sys.stdin is a file object and we can loop it through its iterator:

import sys

for line in sys.stdin:
    if line.strip() == 'exit':
        break
    sys.stdout.write(f">> {line}")

Status Bar

Build a status bar using sys.stdout.write. The \r moves the cursor to the beginning of the line:

import time
import sys

for i in range(101):
    time.sleep(0.1)
    sys.stdout.write(f"{i} [{'#' * i}{'.' * (100 - i)}]\r")
sys.stdout.write('\n')

input() vs. sys.stdin.readline()

Reference

Last updated