Skip to content

Commit 77f35d0

Browse files
authored
Refactor argument parsing with argparse
Refactor command-line argument parsing to use argparse for better handling of options and file inputs.
1 parent f792b20 commit 77f35d0

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

implement-shell-tools/wc/wc-python.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import sys
1+
import argparse
22

33
def count_file(filename):
44

@@ -27,20 +27,19 @@ def format_output(lines, words, chars, filename, show_l, show_w, show_c):
2727
return " ".join(parts)
2828

2929
def main():
30-
args = sys.argv[1:]
31-
32-
l = w = c = False
33-
files = []
34-
35-
for arg in args:
36-
if arg == "-l":
37-
l = True
38-
elif arg == "-w":
39-
w = True
40-
elif arg == "-c":
41-
c = True
42-
elif not arg.startswith("-"):
43-
files.append(arg)
30+
parser = argparse.ArgumentParser(description="wc imlementation in Python")
31+
32+
parser.add_argument("files", nargs="+", help="Files to process")
33+
parser.add_argument("-l", action="store_true", help="Show line count")
34+
parser.add_argument("-w", action="store_true", help="Show word count")
35+
parser.add_argument("-c", action="store_true", help="Show character count")
36+
37+
args = parser.parse_args()
38+
39+
l = args.l
40+
w = args.w
41+
c = args.c
42+
files = args.files
4443

4544
if not (l or w or c):
4645
l = w = c = True
@@ -63,4 +62,4 @@ def main():
6362
print(format_output(total_lines, total_words, total_chars, "total", l, w, c))
6463

6564
if __name__ == "__main__":
66-
main()
65+
main()

0 commit comments

Comments
 (0)