Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions implement-shell-tools/implement-shell-tools-python/cat/cat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
import sys
import argparse


def print_file(file_path, options, counter):
try:
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
stripped = line.rstrip("\n")

should_number = options.number_mode == "all" or (
options.number_mode == "non-empty" and stripped != ""
)

if should_number:
print(f"{counter}\t{stripped}")
counter += 1
else:
print(stripped)

except FileNotFoundError:
print(f"cat: {file_path}: No such file or directory", file=sys.stderr)

return counter


def main():
parser = argparse.ArgumentParser(description="Concatenate files and print output")
parser.add_argument("-n", "--number", action="store_true", help="number all lines")

parser.add_argument(
"-b", "--number-nonblank", action="store_true", help="number non-empty lines"
)

parser.add_argument("files", nargs="+", help="files to read")

args = parser.parse_args()

if args.number_nonblank:
args.number_mode = "non-empty"
elif args.number:
args.number_mode = "all"
else:
args.number_mode = "none"

counter = 1
for file in args.files:
counter = print_file(file, args, counter)


if __name__ == "__main__":
main()
39 changes: 39 additions & 0 deletions implement-shell-tools/implement-shell-tools-python/ls/ls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
import sys
import os
import argparse


def list_directory(path, show_all):
try:
entries = os.listdir(path)

except Exception as e:
print(f"Error reading directory {path}: {e}", file=sys.stderr)
sys.exit(1)
Comment thread
Poonam-raj marked this conversation as resolved.
for entry in sorted(entries):
if not show_all and entry.startswith("."):
continue
print(entry)


def main():
parser = argparse.ArgumentParser(description="List directory contents")
parser.add_argument("-a", "--all", action="store_true", help="show hidden files")
parser.add_argument("paths", nargs="*", default=["."], help="directories to list")
Comment on lines +21 to +23
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if the core functionality will always act like -1 has been passed in, i think we should still take the argument here so ls can be used as described in the instructions


args = parser.parse_args()

dirs = args.paths

for i, path in enumerate(dirs):
if len(dirs) > 1:
print(f"{path}:")
list_directory(path, args.all)

if len(dirs) > 1 and i < len(dirs) - 1:
print("")


if __name__ == "__main__":
main()
70 changes: 70 additions & 0 deletions implement-shell-tools/implement-shell-tools-python/wc/wc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
import sys

def count_file_content(content):
raw_lines = content.split("\n")
lines = len(raw_lines) - 1 if raw_lines[-1] == "" else len(raw_lines)
words = len(content.split())
bytes_ = len(content.encode("utf-8"))
Comment thread
Poonam-raj marked this conversation as resolved.
return lines, words, bytes_


def print_counts(path, counts, options):
Comment thread
Poonam-raj marked this conversation as resolved.
parts = []
if options["line"]:
parts.append(str(counts[0]).rjust(8))
if options["word"]:
parts.append(str(counts[1]).rjust(8))
if options["byte"]:
parts.append(str(counts[2]).rjust(8))

output = "".join(parts)
print(f"{output} {path}")


def main():
args = sys.argv[1:]

options = {"line": False, "word": False, "byte": False}
files = []

for arg in args:
if arg == "-l":
options["line"] = True
elif arg == "-w":
options["word"] = True
elif arg == "-c":
options["byte"] = True
else:
files.append(arg)

if not files:
print("No files specified", file=sys.stderr)
sys.exit(1)

if not any(options.values()):
options = {"line": True, "word": True, "byte": True}
Comment on lines +26 to +46
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again I would say using argparse would take some of the heavy lifting from validating the extracted arguments and sending errors for file etc.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still would like to see a refactor to argparse here if you can


total = [0, 0, 0]
multiple = len(files) > 1

for path in files:
try:
with open(path, "r", encoding="utf-8") as f:
content = f.read()

counts = count_file_content(content)
total = [t + c for t, c in zip(total, counts)]

print_counts(path, counts, options)

except Exception as e:
print(f"Error reading file {path}: {e}", file=sys.stderr)
sys.exit(1)

if multiple:
print_counts("total", total, options)


if __name__ == "__main__":
main()
Loading