Added getchar()
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 1c8197d · Browse files · 8 files·+138 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+138 added−3 removed
- tests:+11 added−0 removed
- other:+127 added−3 removed
Provenance
- Commit
88c97ef- Tree
20ab20f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1c8197d
8 files changed+138 added−3 removed
modified:click/__init__.py+2 added-1 removed
31 unmodified lines32 format_filename, get_app_dir33 34 # Terminal functions35 from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36- progressbar, clear, style, unstyle, secho, edit, launch36+ progressbar, clear, style, unstyle, secho, edit, launch, getchar37 38 # Exceptions39 from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort25 unmodified lines66 67 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',70+ 'getchar',71 72 # Exceptions73 'ClickException', 'UsageError', 'BadParameter', 'FileError',74 'Abort',10 unmodified linesmodified:click/_termui_impl.py+52 added-1 removed
12 unmodified lines13 import sys14 import time15 import math16 from ._compat import _default_text_stdout, range_type, PY2, isatty, \17- open_stream, strip_ansi17+ open_stream, strip_ansi, get_best_encoding18 from .utils import echo19 from .exceptions import ClickException20 21 395 unmodified lines417 import webbrowser418 webbrowser.open(url)419 return 0420 return 1421+422+423+def _translate_ch_to_exc(ch):424+ if ch == '\x03':425+ raise KeyboardInterrupt()426+ if ch == '\x04':427+ raise EOFError()428+429+430+if sys.platform.startswith('win'):431+ import msvcrt432+433+ def getchar(echo):434+ rv = msvcrt.getch()435+ if echo:436+ msvcrt.putchar(rv)437+ _translate_ch_to_exc(rv)438+ if PY2:439+ enc = getattr(sys.stdin, 'encoding', None)440+ if enc is not None:441+ rv = rv.decode(enc, 'replace')442+ else:443+ rv = rv.decode('cp1252', 'replace')444+ return rv445+else:446+ import tty447+ import termios448+449+ def getchar(echo):450+ if not isatty(sys.stdin):451+ f = open('/dev/tty')452+ fd = f.fileno()453+ else:454+ fd = sys.stdin.fileno()455+ f = None456+ try:457+ old_settings = termios.tcgetattr(fd)458+ try:459+ tty.setraw(fd)460+ ch = os.read(fd, 32)461+ if echo and isatty(sys.stdout):462+ sys.stdout.write(ch)463+ finally:464+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)465+ sys.stdout.flush()466+ if f is not None:467+ f.close()468+ except termios.error:469+ pass470+ _translate_ch_to_exc(ch)471+ return ch.decode(get_best_encoding(sys.stdin), 'replace')modified:click/termui.py+27 added
431 unmodified lines432 the filesystem.433 """434 from _termui_impl import open_url435 return open_url(url, wait=wait, locate=locate)436+437+438+# If this is provided, getchar() calls into this instead. This is used439+# for unittesting purposes.440+_getchar = None441+442+443+def getchar(echo=False):444+ """Fetches a single character from the terminal and returns it. This445+ will always return a unicode character and under certain rare446+ circumstances this might return more than one character. The447+ situations which more than one character is returned is when for448+ whatever reason multiple characters end up in the terminal buffer or449+ standard in was not actually a terminal.450+451+ Note that this will always read from the terminal, even if something452+ is piped into the standard input.453+454+ .. versionadded:: 2.0455+456+ :param echo: if set to True the character read will also show up on457+ the terminal. The default is not not show it.458+ """459+ f = _getchar460+ if f is None:461+ from _termui_impl import getchar as f462+ return f(echo)modified:click/testing.py+10 added
170 unmodified lines171 sys.stdout.write((prompt or '') + '\n')172 sys.stdout.flush()173 return input.readline().rstrip('\r\n')174 175+ def _getchar(echo):176+ char = sys.stdin.read(1)177+ if echo:178+ sys.stdout.write(char)179+ sys.stdout.flush()180+ return char181+182 old_visible_prompt_func = click.termui.visible_prompt_func183 old_hidden_prompt_func = click.termui.hidden_prompt_func184+ old__getchar_func = click.termui._getchar185 click.termui.visible_prompt_func = visible_input186 click.termui.hidden_prompt_func = hidden_input187+ click.termui._getchar = _getchar188 189 old_env = {}190 try:191 for key, value in iteritems(env):19 unmodified lines211 sys.stderr = old_stderr212 sys.stdin = old_stdin213 click.termui.visible_prompt_func = old_visible_prompt_func214 click.termui.hidden_prompt_func = old_hidden_prompt_func215+ click.termui._getchar = old__getchar_func216 217 def invoke(self, cli, args=None, input=None, env=None, **extra):218 """Invokes a command in an isolated environment. The arguments are219 forwarded directly to the command line script, the `extra` keyword49 unmodified linesmodified:docs/api.rst+3 added-1 removed
54 unmodified lines55 .. autofunction:: edit56 57 .. autofunction:: launch58 59-.. autofunction:: format_filename59+.. autofunction:: getchar60 61 .. autofunction:: get_terminal_size62 63 .. autofunction:: get_binary_stream1 unmodified line65 .. autofunction:: get_text_stream66 67 .. autofunction:: get_app_dir68 69+.. autofunction:: format_filename70+71 Commands72 --------73 74 .. autoclass:: BaseCommand91 unmodified linesmodified:docs/utils.rst+32 added
91 unmodified lines92 import click93 click.clear()94 95 96+Getting Characters from Terminal97+--------------------------------98+99+.. versionadded:: 2.0100+101+Normally when reading input from the terminal you would use reading from102+standard input. However this is buffered input and will not show up until103+the line has been terminated. In certain circumstances you might not want104+to do that and instead read individual characters as they are being105+written.106+107+For this click provides the :func:`getchar` function which reads a single108+character from the terminal buffer and returns it as unicode character.109+110+Note that this function will always read from the terminal, even if stdin111+is instead a pipe.112+113+Example::114+115+ import click116+117+ click.echo('Continue? [yn] ', nl=False)118+ c = click.getchar()119+ click.echo()120+ if c == 'y':121+ click.echo('We will go on')122+ elif c == 'n':123+ click.echo('Abort!')124+ else:125+ click.echo('Invalid input :(')126+127+128 Launching Editors129 -----------------130 131 .. versionadded:: 2.0160 unmodified linesmodified:tests/test_testing.py+11 added
75 unmodified lines76 runner = CliRunner()77 result = runner.invoke(test, input='wau wau\n')78 assert not result.exception79 assert result.output == 'Foo: \nfoo=wau wau\n'80+81+82+def test_getchar():83+ @click.command()84+ def continue_it():85+ click.echo(click.getchar())86+87+ runner = CliRunner()88+ result = runner.invoke(continue_it, input='y')89+ assert not result.exception90+ assert result.output == 'y\n'modified:CHANGES+1 added
30 unmodified lines31 the required flag. It defaults to not required.32 - setting a default for arguments now implicitly makes it non required.33 - changed "yN" / "Yn" to "y/N" and "Y/n" in confirmation prompts.34 - added basic support for bash completion.35+- added :func:`getchar` to fetch a single character from the terminal.36 37 Version 1.138 -----------39 11 unmodified lines