1
0
forked from tdwojak/Python2017

Zadanie domowe Zad4

Labs05 - task04
Rozwiązanie s45146
This commit is contained in:
s45146 2017-12-20 21:03:42 +01:00
parent 2e6466143b
commit ef426e0c64

View File

@ -7,6 +7,7 @@ Zwraca liczbę słów, znaków i linii.
""" """
import sys import sys
import argparse
def count_lines(text): def count_lines(text):
@ -29,11 +30,50 @@ def wc(text):
chars = count_chars(text) chars = count_chars(text)
return lines, words, chars 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(): def main():
""" 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__": if __name__ == "__main__":
main() main()