Skip to content

Commit f792b20

Browse files
authored
Replace sys.argv with argparse in ls-python.py
Refactor ls command to use argparse for argument parsing.
1 parent 2d8a282 commit f792b20

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed
Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
1-
import sys
1+
import argparse
22
import os
33

44
def main():
5-
args = sys.argv[1:]
6-
7-
path = "."
8-
one_per_line = False
9-
show_hidden = False
10-
11-
for arg in args:
12-
if arg == "-a":
13-
show_hidden = True
14-
elif arg == "-1":
15-
one_per_line = True
16-
elif not arg.startswith("-"):
17-
path = arg
5+
parser = argparse.ArgumentParser(description=" ls in Python")
6+
7+
parser.add_argument("path", nargs="?", default=".", help="Directory to list")
8+
parser.add_argument("-a", action="store_true", help="Show hidden files")
9+
parser.add_argument("-1", dest="one_per_line", action="store_true",
10+
help="List one file per line")
11+
12+
args = parser.parse_args()
13+
14+
path = args.path
15+
show_hidden = args.a
16+
one_per_line = args.one_per_line
1817

1918
entries = os.listdir(path)
2019

@@ -30,4 +29,4 @@ def main():
3029
print(" ".join(entries))
3130

3231
if __name__ == "__main__":
33-
main()
32+
main()

0 commit comments

Comments
 (0)