Skip to content

Commit 4f141b3

Browse files
committed
Implement ls commands in python
1 parent 1bce56a commit 4f141b3

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

implement-shell-tools/ls/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,8 @@ It must act the same as `ls` would, if run from the directory containing this RE
1313
Matching any additional behaviours or flags are optional stretch goals.
1414

1515
We recommend you start off supporting just `-1`, then adding support for `-a`.
16+
17+
*=======command for running the script===========
18+
python3 ls_py.py -1
19+
python3 ls_py.py -1 sample-files
20+
python3 ls_py.py -1 -a sample-files

implement-shell-tools/ls/ls_py.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import os
5+
import sys
6+
7+
8+
# Set up the argument parser
9+
def parse_args():
10+
parser = argparse.ArgumentParser(
11+
prog="list_files_in_directory",
12+
description="Implement ls commands to list files in directory"
13+
)
14+
15+
parser.add_argument(
16+
"-1","--file-per-line",
17+
action="store_true",
18+
dest="file_per_line",
19+
help="list files one per line"
20+
)
21+
22+
parser.add_argument(
23+
"-a",
24+
"--files-and-hidden-ones",
25+
action="store_true",
26+
dest="files_and_hidden_ones",
27+
help="list all files including hidden ones",
28+
)
29+
30+
parser.add_argument(
31+
"paths",
32+
nargs="*",
33+
help="directories to list"
34+
)
35+
36+
return parser.parse_args()
37+
38+
# if no paths, default to current directory
39+
def get_paths(args):
40+
if len(args.paths) == 0:
41+
return ["."]
42+
return args.paths
43+
44+
# list a single directory
45+
def list_directory(directory_path, show_hidden, file_per_line):
46+
try:
47+
entries = os.listdir(directory_path)
48+
except OSError as err:
49+
print(f"ls: cannot access '{directory_path}': {err}", file=sys.stderr)
50+
return
51+
52+
if not show_hidden:
53+
entries = [name for name in entries if not name.startswith(".")]
54+
55+
if file_per_line:
56+
for name in entries:
57+
print(name)
58+
else:
59+
print(" ".join(entries))
60+
61+
def main():
62+
args = parse_args()
63+
paths = get_paths(args)
64+
65+
for directory_path in paths:
66+
list_directory(
67+
directory_path=directory_path,
68+
show_hidden=args.files_and_hidden_ones,
69+
file_per_line=args.file_per_line,
70+
)
71+
72+
if __name__ == "__main__":
73+
main()

0 commit comments

Comments
 (0)