Python Notes and Examples

stdin, stdout, stderr

To get input from the user on stdin:

s = input("Today's comment?: ")
# `s` won't have a newline at the end.

Printing to stdout:

print('hey')                   # With newline.
print('hey', end='')           # No newline.
print('a', 'b', 'c', sep=':')  # Prints "a:b:c".
print('bye', flush=True)       # Flush the stream.

Print to stderr:

import sys
print('hi', file=sys.stderr)

See also help(print).

Note that you can write backspaces to stdout to overwrite what’s there:

import sys

write, flush = sys.stdout.write, sys.stdout.flush
s = 'hello'
write(s)
flush()
write('\x08' * len(s))
flush()
write('j')  # shows: jello

and

for c in itertools.cycle('|/-\\'):
    write(c)
    flush()
    time.sleep(0.1)
    write('\x08')