HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Constraining stdin in Python, v2.0

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stdinconstrainingpython

Problem

Rags, again.

This is the rewrite of Read stdin like a dictator.

From that post:

All too often I find myself wanting to allow only a certain list of characters to be written to stdin, and only recently did I actually bother to implement it. In Python, of all languages!

Essentially, this module provides a few APIs that allow a very tailored approach to reading characters from a terminal. By intercepting individual keypresses at the instant they occur, we can make cool decisions about closing the input stream whenever we want -- we dictate who says what in our terminal!

The standard input stream, after being opened, can be closed after a number of characters, or, at caller's option, any combination of a number of characters and allowed inputs.

... Yep, all still true, just way better, and actually cross-platform now.

It might seem like there's a lot of dead code / overkill stuff here; that's because I'm about to shift its focus from "input-constrainer-thing" to "poor-man's libreadline/curses" and so there's some provisioning in effect, but nevermind that.

I have some unittests but I won't supply them because writing them for an IO module is a lot more work than they're worth at this point.

```
#!/usr/bin/env python3

import sys
import struct
from platform import system
SYSTEM = system().lower()

class CHAR:
"""essentially an enum, to avoid clouding the ns"""
NUL = chr(0)
INT = chr(3)
EOF = chr(4)
BEL = chr(7)
BKS = chr(8)
LFD = chr(10)
CRR = chr(13)
ESC = chr(27)
SPC = chr(32)
DEL = chr(127)

CONDS = [
(lambda i, chars: i in chars),
(lambda i, chars: i not in chars),
(lambda *args, **kwargs: False),
]

def init(TERM_BUFSIZE=4096):
"""module initialiser: calls constructors so you don't have to
you must call this before other functions!"""
global reader
reader = read_class(TERMCTL_SPECIAL_BUFSIZE=TERM_BUFSIZE)

def checkinit(func, *args, **kwargs):

def isdefined(*arg

Solution

Take care of the docs

Please avoid destroying your documentation after writing it. checkinit destroys the documentation of the functions it is applied to. You should use functools.wraps.

Context

StackExchange Code Review Q#121031, answer score: 3

Revisions (0)

No revisions yet.