Skip to content

Commit 0c432f3

Browse files
committed
python implementation of ls to mimick ls behavior
1 parent 4969b17 commit 0c432f3

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import argparse
2+
import os #interacting with the filesystem (paths, directories)
3+
import sys #access to system streams (stdout, stderr) and arguments
4+
5+
def parseargs():
6+
parser = argparse.ArgumentParser(
7+
prog = "ls",
8+
description = "ls clone to -1 and -a flags"
9+
)
10+
parser.add_argument("-1", dest = "one_per_line", action = "store_true",help = "List one file per line") #dest sets the attribute name in parsed argument.
11+
parser.add_argument("-a", "--all", action ="store_true",help = "Include directory entries whose names begin with a dot (.)")
12+
parser.add_argument("dirs", nargs = "*", default = ["."], help = "Directories to list (default is current directory)")
13+
return parser.parse_args()
14+
15+
def print_directory_entries(path, one_per_line=False, show_all=False):
16+
try:
17+
# Retrieve all entries (files and subdirectories) inside the given path
18+
directory_entries = os.listdir(path)
19+
except FileNotFoundError:
20+
# If the directory doesn't exist, print an error to stderr
21+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
22+
return
23+
except PermissionError:
24+
# If the directory exists but we don't have permission, print an error
25+
print(f"ls: cannot open directory '{path}': Permission denied", file=sys.stderr)
26+
return
27+
28+
# By default, ls hides "dotfiles" (names starting with ".").
29+
# Only include them if the -a flag (show_all=True) is set.
30+
if not show_all:
31+
directory_entries = [entry for entry in directory_entries if not entry.startswith(".")]
32+
33+
# Sort entries alphabetically for consistent output
34+
directory_entries.sort()
35+
36+
if one_per_line:
37+
# If -1 flag is set, print each entry on its own line
38+
for entry_name in directory_entries:
39+
print(entry_name)
40+
else:
41+
# Default behavior: print entries space-separated on one line
42+
print(" ".join(directory_entries))
43+
44+
def main():
45+
args = parseargs()
46+
# Loop through each directory provided
47+
for directory in args.dirs:
48+
print_directory_entries(
49+
directory,
50+
one_per_line = args.one_per_line,
51+
show_all = args.all
52+
)
53+
if __name__ == "__main__":
54+
main()

0 commit comments

Comments
 (0)