Moved unbuffered stdin code to console.py

This commit is contained in:
Sam Colwell 2019-02-09 13:53:34 -05:00
parent 0c78f33b43
commit 99b7f66070
2 changed files with 37 additions and 24 deletions

View File

@ -54,31 +54,13 @@ class Monitor(cmd.Cmd):
self.prompt = "."
self._add_shortcuts()
# Attempt to get a copy of stdin that is unbuffered.
# This allows for immediate response to typed input as well as
# pasted input. If unable to get an unbuffered version of
# stdin, use the original version.
if stdin != None:
try:
# Reopen stdin with no buffer.
self.unbuffered_stdin = os.fdopen(stdin.fileno(), 'rb', 0)
except Exception as e:
print(e)
# Unable to reopen this file handle with no buffer.
# Just use the original file handle.
print("Error opening unbuffered stdin - using buffered version")
self.unbuffered_stdin = stdin
else:
# If stdin is None, try using sys.stdin for input.
try:
# Reopen the system's stdin with no buffer.
self.unbuffered_stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
except Exception as e:
print(e)
print("Error opening default unbuffered stdin - using buffered version")
self.unbuffered_stdin = None
# Attempt to get a copy of stdin that is unbuffered on systems
# that support it. This allows for immediate response to
# typed input as well as pasted input. If unable to get an
# unbuffered version of stdin, the original version is returned.
stdin = console.get_unbuffered_stdin(stdin)
cmd.Cmd.__init__(self, stdin=self.unbuffered_stdin, stdout=stdout)
cmd.Cmd.__init__(self, stdin=stdin, stdout=stdout)
# Save the current input mode so it can be restored after
# after processing commands and before exiting.

View File

@ -3,6 +3,10 @@ import sys
if sys.platform[:3] == "win":
import msvcrt
def get_unbuffered_stdin(stdin):
""" get_unbuffered_stdin returns the given stdin on Windows. """
return stdin
def save_mode(stdin):
""" save_mode is a no-op on Windows. """
return
@ -37,10 +41,37 @@ if sys.platform[:3] == "win":
else:
import termios
import os
from select import select
oldattr = None
def get_unbuffered_stdin(stdin):
""" Attempt to get and return a copy of stdin that is
unbuffered. This allows for immediate response to typed input
as well as pasted input. If unable to get an unbuffered
version of stdin, return the original version.
"""
if stdin != None:
try:
# Reopen stdin with no buffer.
return os.fdopen(stdin.fileno(), 'rb', 0)
except Exception as e:
print(e)
# Unable to reopen this file handle with no buffer.
# Just use the original file handle.
print("Error opening unbuffered stdin - using buffered version")
return stdin
else:
# If stdin is None, try using sys.stdin for input.
try:
# Reopen the system's stdin with no buffer.
return os.fdopen(sys.stdin.fileno(), 'rb', 0)
except Exception as e:
print(e)
print("Error opening default unbuffered stdin - using buffered version")
return None
def save_mode(stdin):
""" For operating systems that support it, save the original
input termios settings so they can be restored later. This