From ef426e0c6448d054fba925afc5875eb858a14aa6 Mon Sep 17 00:00:00 2001 From: s45146 Date: Wed, 20 Dec 2017 21:03:42 +0100 Subject: [PATCH] =?UTF-8?q?Zadanie=20domowe=20Zad4=20Labs05=20-=20task04?= =?UTF-8?q?=20Rozwi=C4=85zanie=20s45146?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- labs05/task04.py | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/labs05/task04.py b/labs05/task04.py index 4dfc78c..cfebfcb 100644 --- a/labs05/task04.py +++ b/labs05/task04.py @@ -7,6 +7,7 @@ Zwraca liczbę słów, znaków i linii. """ import sys +import argparse def count_lines(text): @@ -29,11 +30,50 @@ def wc(text): chars = count_chars(text) return lines, words, chars +#Moja klasa wyjątku +class ArgException(Exception): + def __init__(self, text): + self.text = text + def __str__(self): + return self.text def main(): """ main """ - print(wc(sys.stdin.read())) + msg_usage = "Usage: task04.py [-h | -l | -w | -c] [file_name | stdin]" + parser = argparse.ArgumentParser() + parser.add_argument("-l", help="-l returns number of lines", action = 'store_true') + parser.add_argument("-w", help="-w returns number of words", action = 'store_true') + parser.add_argument("-c", help="-c returns number of characters", action = 'store_true') + parser.add_argument("file_name", help="This is path to the text input file to read the lines from or stdin if not given", type = argparse.FileType('rt'), nargs='?') + args = parser.parse_args() + if args.l + args.w + args.c > 1: #Jeśli więcej niż 1 argument {-l, -w, -c} + print(msg_usage, "\nToo many arguments passed!") + #print(args.l, args.w, args.c, args.input) + return + res = "" #Zwracany napis + + if args.file_name is None: + fh_lines = sys.stdin.read() + else: + fh_lines = args.file_name.read() + + if args.l: + res = count_lines(fh_lines) + elif args.w: + res = count_words(fh_lines) + elif args.c: + res = count_chars(fh_lines) + elif not (args.l and args.w and args.c): + res = wc(fh_lines) + else: #Coś jest nie tak! + raise ArgException(msg_usage, "\nError in arguments!") + + #print(wc(sys.stdin.read())) + # print(wc(fh_lines)) + + #print(fh_lines) + print(res) if __name__ == "__main__": main()