Skip to content
Myr

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

8 files+138 added−3 removed

modified:click/__init__.py+2 added-1 removed
31 unmodified lines
32 format_filename, get_app_dir3334# Terminal functions35from .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, getchar3738# Exceptions39from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort
25 unmodified lines
6667 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',70 'getchar',7172 # Exceptions73 'ClickException', 'UsageError', 'BadParameter', 'FileError',74 'Abort',
10 unmodified lines
modified:click/_termui_impl.py+52 added-1 removed
12 unmodified lines
13import sys14import time15import math16from ._compat import _default_text_stdout, range_type, PY2, isatty, \17 open_stream, strip_ansi17 open_stream, strip_ansi, get_best_encoding18from .utils import echo19from .exceptions import ClickException2021
395 unmodified lines
417 import webbrowser418 webbrowser.open(url)419 return 0420 return 1421422423def _translate_ch_to_exc(ch):424 if ch == '\x03':425 raise KeyboardInterrupt()426 if ch == '\x04':427 raise EOFError()428429430if sys.platform.startswith('win'):431 import msvcrt432433 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 rv445else:446 import tty447 import termios448449 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 lines
432 the filesystem.433 """434 from _termui_impl import open_url435 return open_url(url, wait=wait, locate=locate)436437438# If this is provided, getchar() calls into this instead. This is used439# for unittesting purposes.440_getchar = None441442443def 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.450451 Note that this will always read from the terminal, even if something452 is piped into the standard input.453454 .. versionadded:: 2.0455456 :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 lines
171 sys.stdout.write((prompt or '') + '\n')172 sys.stdout.flush()173 return input.readline().rstrip('\r\n')174175 def _getchar(echo):176 char = sys.stdin.read(1)177 if echo:178 sys.stdout.write(char)179 sys.stdout.flush()180 return char181182 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 = _getchar188189 old_env = {}190 try:191 for key, value in iteritems(env):
19 unmodified lines
211 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_func216217 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` keyword
49 unmodified lines
modified:docs/api.rst+3 added-1 removed
54 unmodified lines
55.. autofunction:: edit5657.. autofunction:: launch5859.. autofunction:: format_filename59.. autofunction:: getchar6061.. autofunction:: get_terminal_size6263.. autofunction:: get_binary_stream
1 unmodified line
65.. autofunction:: get_text_stream6667.. autofunction:: get_app_dir6869.. autofunction:: format_filename7071Commands72--------7374.. autoclass:: BaseCommand
91 unmodified lines
modified:docs/utils.rst+32 added
91 unmodified lines
92 import click93 click.clear()949596Getting Characters from Terminal97--------------------------------9899.. versionadded:: 2.0100101Normally when reading input from the terminal you would use reading from102standard input. However this is buffered input and will not show up until103the line has been terminated. In certain circumstances you might not want104to do that and instead read individual characters as they are being105written.106107For this click provides the :func:`getchar` function which reads a single108character from the terminal buffer and returns it as unicode character.109110Note that this function will always read from the terminal, even if stdin111is instead a pipe.112113Example::114115 import click116117 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 :(')126127128Launching Editors129-----------------130131.. versionadded:: 2.0
160 unmodified lines
modified:tests/test_testing.py+11 added
75 unmodified lines
76 runner = CliRunner()77 result = runner.invoke(test, input='wau wau\n')78 assert not result.exception79 assert result.output == 'Foo: \nfoo=wau wau\n'808182def test_getchar():83 @click.command()84 def continue_it():85 click.echo(click.getchar())8687 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 lines
31 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.3637Version 1.138-----------39
11 unmodified lines