def get_trimmed_history(self, maxlength):
if maxlength >= 0:
cut = len(self.history) - maxlength
if cut < 0:
cut = 0
else:
cut = 0
return self.history[cut:]
# --- simplified support for reading multiline Python statements ---
# This duplicates small parts of pyrepl.python_reader. I'm not
# reusing the PythonicReader class directly for two reasons. One is
# to try to keep as close as possible to CPython's prompt. The
# other is that it is the readline module that we are ultimately
# implementing here, and I don't want the built-in raw_input() to
# start trying to read multiline inputs just because what the user
# typed look like valid but incomplete Python code. So we get the
# multiline feature only when using the multiline_input() function
# directly (see _pypy_interact.py).
python类raw_input()的实例源码
def yes_no_input(msg):
if hasattr(__builtin__, 'raw_input'):
input = __builtin__.raw_input
else:
input = builtins.input
try:
choice = input("{} [y/N]: ".format(msg)).lower()
while True:
if choice in ['y', 'ye', 'yes']:
return True
elif choice in ['n', 'no']:
return False
else:
choice = input(
"Please respond with 'yes' or 'no' [y/N]: ").lower()
except (EOFError, KeyboardInterrupt):
return False
def get_trimmed_history(self, maxlength):
if maxlength >= 0:
cut = len(self.history) - maxlength
if cut < 0:
cut = 0
else:
cut = 0
return self.history[cut:]
# --- simplified support for reading multiline Python statements ---
# This duplicates small parts of pyrepl.python_reader. I'm not
# reusing the PythonicReader class directly for two reasons. One is
# to try to keep as close as possible to CPython's prompt. The
# other is that it is the readline module that we are ultimately
# implementing here, and I don't want the built-in raw_input() to
# start trying to read multiline inputs just because what the user
# typed look like valid but incomplete Python code. So we get the
# multiline feature only when using the multiline_input() function
# directly (see _pypy_interact.py).
def after_command(self, cmd):
super(ReadlineAlikeReader, self).after_command(cmd)
if self.more_lines is None:
# Force single-line input if we are in raw_input() mode.
# Although there is no direct way to add a \n in this mode,
# multiline buffers can still show up using various
# commands, e.g. navigating the history.
try:
index = self.buffer.index("\n")
except ValueError:
pass
else:
self.buffer = self.buffer[:index]
if self.pos > len(self.buffer):
self.pos = len(self.buffer)
def raw_input(self, prompt=''):
try:
reader = self.get_reader()
except _error:
return _old_raw_input(prompt)
reader.ps1 = prompt
return reader.readline(startup_hook=self.startup_hook)
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def setUp(self):
self.raw_input_holder = __builtin__.raw_input
self.stdout = sys.stdout
sys.stdout = self.buf = StringIO.StringIO()
def tearDown(self):
sys.stdout = self.stdout
__builtin__.raw_input = self.raw_input_holder
def test_register(self, mock_get_pass, mock_create, mock_save):
output = '''Please input username and password of the registry:
repository_name'''
__builtin__.raw_input = lambda _: 'username' # set username
repository = dockercloudcli.commands.dockercloud.Repository()
repository.name = 'repository_name'
mock_create.return_value = repository
repository_register('repository', None, None)
self.assertEqual(output, self.buf.getvalue().strip())
self.buf.truncate(0)
def test_register_with_exception(self, mock_get_pass, mock_create, mock_exit):
__builtin__.raw_input = lambda _: 'username' # set username
repository_register('repository', None, None)
mock_exit.assert_called_with(EXCEPTION_EXIT_CODE)
def init():
# defer imports until initialization
import sys, __builtin__
from ..util import safeeval
class Wrapper:
def __init__(self, fd):
self._fd = fd
def readline(self, size = None):
return readline(size)
def __getattr__(self, k):
return self._fd.__getattribute__(k)
sys.stdin = Wrapper(sys.stdin)
def raw_input(prompt = '', float = True):
"""raw_input(prompt = '', float = True)
Replacement for the built-in `raw_input` using ``pwnlib``s readline
implementation.
Arguments:
prompt(str): The prompt to show to the user.
float(bool): If set to `True`, prompt and input will float to the
bottom of the screen when `term.term_mode` is enabled.
"""
return readline(None, prompt, float)
__builtin__.raw_input = raw_input
def input(prompt = '', float = True):
"""input(prompt = '', float = True)
Replacement for the built-in `input` using ``pwnlib``s readline
implementation, and `pwnlib.util.safeeval.expr` instead of `eval` (!).
Arguments:
prompt(str): The prompt to show to the user.
float(bool): If set to `True`, prompt and input will float to the
bottom of the screen when `term.term_mode` is enabled.
"""
return safeeval.const(readline(None, prompt, float))
__builtin__.input = input
def raw_input(prompt=''):
#the original raw_input would only remove a trailing \n, so, at
#this point if we had a \r\n the \r would remain (which is valid for eclipse)
#so, let's remove the remaining \r which python didn't expect.
ret = original_raw_input(prompt)
if ret.endswith('\r'):
return ret[:-1]
return ret
def input(prompt=''):
#input must also be rebinded for using the new raw_input defined
return eval(raw_input(prompt))
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def after_command(self, cmd):
super(ReadlineAlikeReader, self).after_command(cmd)
if self.more_lines is None:
# Force single-line input if we are in raw_input() mode.
# Although there is no direct way to add a \n in this mode,
# multiline buffers can still show up using various
# commands, e.g. navigating the history.
try:
index = self.buffer.index("\n")
except ValueError:
pass
else:
self.buffer = self.buffer[:index]
if self.pos > len(self.buffer):
self.pos = len(self.buffer)
def raw_input(self, prompt=''):
try:
reader = self.get_reader()
except _error:
return _old_raw_input(prompt)
reader.ps1 = prompt
return reader.readline(startup_hook=self.startup_hook)
def _setup():
global _old_raw_input
if _old_raw_input is not None:
return # don't run _setup twice
try:
f_in = sys.stdin.fileno()
f_out = sys.stdout.fileno()
except (AttributeError, ValueError):
return
if not os.isatty(f_in) or not os.isatty(f_out):
return
_wrapper.f_in = f_in
_wrapper.f_out = f_out
if '__pypy__' in sys.builtin_module_names: # PyPy
def _old_raw_input(prompt=''):
# sys.__raw_input__() is only called when stdin and stdout are
# as expected and are ttys. If it is the case, then get_reader()
# should not really fail in _wrapper.raw_input(). If it still
# does, then we will just cancel the redirection and call again
# the built-in raw_input().
try:
del sys.__raw_input__
except AttributeError:
pass
return raw_input(prompt)
sys.__raw_input__ = _wrapper.raw_input
else:
# this is not really what readline.c does. Better than nothing I guess
import __builtin__
_old_raw_input = __builtin__.raw_input
__builtin__.raw_input = _wrapper.raw_input
def init():
# defer imports until initialization
import sys, __builtin__
from ..util import safeeval
class Wrapper:
def __init__(self, fd):
self._fd = fd
def readline(self, size = None):
return readline(size)
def __getattr__(self, k):
return self._fd.__getattribute__(k)
sys.stdin = Wrapper(sys.stdin)
def raw_input(prompt = '', float = True):
"""raw_input(prompt = '', float = True)
Replacement for the built-in `raw_input` using ``pwnlib``s readline
implementation.
Arguments:
prompt(str): The prompt to show to the user.
float(bool): If set to `True`, prompt and input will float to the
bottom of the screen when `term.term_mode` is enabled.
"""
return readline(None, prompt, float)
__builtin__.raw_input = raw_input
def input(prompt = '', float = True):
"""input(prompt = '', float = True)
Replacement for the built-in `input` using ``pwnlib``s readline
implementation, and `pwnlib.util.safeeval.expr` instead of `eval` (!).
Arguments:
prompt(str): The prompt to show to the user.
float(bool): If set to `True`, prompt and input will float to the
bottom of the screen when `term.term_mode` is enabled.
"""
return safeeval.const(readline(None, prompt, float))
__builtin__.input = input
def raw_input(prompt=""):
"""raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading."""
sys.stderr.flush()
tty = STDIN.is_a_TTY() and STDOUT.is_a_TTY()
if RETURN_UNICODE:
if tty:
line_bytes = readline(prompt)
line = stdin_decode(line_bytes)
else:
line = stdio_readline(prompt)
else:
if tty:
line = readline(prompt)
else:
line_unicode = stdio_readline(prompt)
line = stdin_encode(line_unicode)
if line:
return line[:-1] # strip strailing "\n"
else:
raise EOFError
def input(prompt=""):
"""input([prompt]) -> value
Equivalent to eval(raw_input(prompt))."""
string = stdin_decode(raw_input(prompt))
caller_frame = sys._getframe(1)
globals = caller_frame.f_globals
locals = caller_frame.f_locals
return eval(string, globals, locals)
def enable(return_unicode=RETURN_UNICODE):
global RETURN_UNICODE
RETURN_UNICODE = return_unicode
builtins.raw_input = raw_input
builtins.input = input
def disable():
builtins.raw_input = original_raw_input
builtins.input = original_input
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def input(prompt=''):
return builtin_mod.raw_input(prompt)
def _setup():
global _old_raw_input
if _old_raw_input is not None:
return
# don't run _setup twice
try:
f_in = sys.stdin.fileno()
f_out = sys.stdout.fileno()
except (AttributeError, ValueError):
return
if not os.isatty(f_in) or not os.isatty(f_out):
return
_wrapper.f_in = f_in
_wrapper.f_out = f_out
if '__pypy__' in sys.builtin_module_names: # PyPy
def _old_raw_input(prompt=''):
# sys.__raw_input__() is only called when stdin and stdout are
# as expected and are ttys. If it is the case, then get_reader()
# should not really fail in _wrapper.raw_input(). If it still
# does, then we will just cancel the redirection and call again
# the built-in raw_input().
try:
del sys.__raw_input__
except AttributeError:
pass
return raw_input(prompt)
sys.__raw_input__ = _wrapper.raw_input
else:
# this is not really what readline.c does. Better than nothing I guess
import __builtin__
try:
import __builtin__
_old_raw_input = __builtin__.raw_input
__builtin__.raw_input = _wrapper.raw_input
except ImportError:
import builtins
_old_raw_input = builtins.input
builtins.input = _wrapper.raw_input