From f8387990b3af739355e91ab3498fc7ff7483a877 Mon Sep 17 00:00:00 2001 From: Dan Blanchard Date: Tue, 19 Jan 2021 13:29:58 -0500 Subject: [PATCH] Add --minimal flag to chardetect command --- chardet/cli/chardetect.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/chardet/cli/chardetect.py b/chardet/cli/chardetect.py index c8d8f00e..4959ad6e 100644 --- a/chardet/cli/chardetect.py +++ b/chardet/cli/chardetect.py @@ -20,7 +20,7 @@ from ..universaldetector import UniversalDetector -def description_of(lines, name="stdin"): +def description_of(lines, name="stdin", minimal=False): """ Return a string describing the probable encoding of a file or list of strings. @@ -39,10 +39,11 @@ def description_of(lines, name="stdin"): break u.close() result = u.result + if minimal: + return result["encoding"] if result["encoding"]: return f'{name}: {result["encoding"]} with confidence {result["confidence"]}' - else: - return f"{name}: no result" + return f"{name}: no result" def main(argv=None): @@ -55,17 +56,22 @@ def main(argv=None): """ # Get command line arguments parser = argparse.ArgumentParser( - description="Takes one or more file paths and reports their detected \ - encodings" + description=( + "Takes one or more file paths and reports their detected encodings" + ) ) parser.add_argument( "input", - help="File whose encoding we would like to determine. \ - (default: stdin)", + help="File whose encoding we would like to determine. (default: stdin)", type=argparse.FileType("rb"), nargs="*", default=[sys.stdin.buffer], ) + parser.add_argument( + "--minimal", + help="Print only the encoding to standard output", + action="store_true", + ) parser.add_argument( "--version", action="version", version=f"%(prog)s {__version__}" ) @@ -80,7 +86,7 @@ def main(argv=None): "--help\n", file=sys.stderr, ) - print(description_of(f, f.name)) + print(description_of(f, f.name, minimal=args.minimal)) if __name__ == "__main__":