我们从Python开源项目中,提取了以下3个代码示例,用于说明如何使用click.getchar()。
def prompt_overwrite(file_name): # Skip if file doesn't exist if not os.path.exists(file_name): return True # Prompt for file overwrite if outfile already exists fmt = "File ({}) already exists. Do you want to overwrite? (y/n): " message = fmt.format(file_name) click.secho(message, nl=False, fg="red") choice = click.getchar() click.echo() if choice not in ("y", "Y"): return False return True
def getch(): mainKeyCode = click.getchar() if mainKeyCode == KeyboardWork.EXT_KEY_PREFIX: extendedKeyCode = click.getchar() return mainKeyCode, extendedKeyCode extendedKeyCode = None return (mainKeyCode, extendedKeyCode)
def view(visualization_path, index_extension): # Guard headless envs from having to import anything large import sys if not os.getenv("DISPLAY") and sys.platform != "darwin": raise click.UsageError( 'Visualization viewing is currently not supported in headless ' 'environments. You can view Visualizations (and Artifacts) at ' 'https://view.qiime2.org, or move the Visualization to an ' 'environment with a display and view it with `qiime tools view`.') import zipfile import qiime2.sdk if index_extension.startswith('.'): index_extension = index_extension[1:] try: visualization = qiime2.sdk.Visualization.load(visualization_path) # TODO: currently a KeyError is raised if a zipped file that is not a # QIIME 2 result is passed. This should be handled better by the framework. except (zipfile.BadZipFile, KeyError, TypeError): raise click.BadParameter( '%s is not a QIIME 2 Visualization. Only QIIME 2 Visualizations ' 'can be viewed.' % visualization_path) index_paths = visualization.get_index_paths(relative=False) if index_extension not in index_paths: raise click.BadParameter( 'No index %s file with is present in the archive. Available index ' 'extensions are: %s' % (index_extension, ', '.join(index_paths.keys()))) else: index_path = index_paths[index_extension] launch_status = click.launch(index_path) if launch_status != 0: click.echo('Viewing visualization failed while attempting to ' 'open %s' % index_path, err=True) else: while True: click.echo( "Press the 'q' key, Control-C, or Control-D to quit. This " "view may no longer be accessible or work correctly after " "quitting.", nl=False) # There is currently a bug in click.getchar where translation # of Control-C and Control-D into KeyboardInterrupt and # EOFError (respectively) does not work on Python 3. The code # here should continue to work as expected when the bug is # fixed in Click. # # https://github.com/pallets/click/issues/583 try: char = click.getchar() click.echo() if char in {'q', '\x03', '\x04'}: break except (KeyboardInterrupt, EOFError): break