Skip to content

Commit 86d1945

Browse files
committed
fix the issues
1 parent d613e7a commit 86d1945

2 files changed

Lines changed: 53 additions & 69 deletions

File tree

  • implement-shell-tools/implement-shell-tools-python

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

Lines changed: 35 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,52 @@
11
#!/usr/bin/env python3
22
import sys
3-
import os
3+
import argparse
44

5-
global_line_counter = 1
65

7-
def print_file(file_path, options):
8-
global global_line_counter
6+
def print_file(file_path, options, counter):
97
try:
108
with open(file_path, "r", encoding="utf-8") as f:
11-
content = f.read()
9+
for line in f:
10+
stripped = line.rstrip("\n")
1211

13-
lines = content.split("\n")
14-
if lines and lines[-1] == "":
15-
lines.pop()
12+
should_number = options.number_mode == "all" or (
13+
options.number_mode == "non-empty" and stripped != ""
14+
)
1615

17-
for line in lines:
18-
prefix = ""
16+
if should_number:
17+
print(f"{counter}\t{stripped}")
18+
counter += 1
19+
else:
20+
print(stripped)
1921

20-
should_number = (
21-
options["number_mode"] == "all" or
22-
(options["number_mode"] == "non-empty" and line.strip() != "")
23-
)
22+
except FileNotFoundError:
23+
print(f"cat: {file_path}: No such file or directory", file=sys.stderr)
2424

25-
if should_number:
26-
prefix = f"{global_line_counter:6}\t"
27-
global_line_counter += 1
25+
return counter
2826

29-
sys.stdout.write(prefix + line + "\n")
3027

31-
except Exception as e:
32-
print(f"cat: {file_path}: {e}", file=sys.stderr)
33-
sys.exit(1)
28+
def main():
29+
parser = argparse.ArgumentParser(description="Concatenate files and print output")
30+
parser.add_argument("-n", "--number", action="store_true", help="number all lines")
3431

32+
parser.add_argument(
33+
"-b", "--number-nonblank", action="store_true", help="number non-empty lines"
34+
)
3535

36-
def main():
37-
global global_line_counter
38-
args = sys.argv[1:]
39-
40-
options = {"number_mode": "off"}
41-
files = []
42-
43-
for arg in args:
44-
if arg == "-n":
45-
options["number_mode"] = "all"
46-
elif arg == "-b":
47-
options["number_mode"] = "non-empty"
48-
else:
49-
files.append(arg)
50-
51-
if not files:
52-
print("cat: missing file operand", file=sys.stderr)
53-
sys.exit(1)
54-
55-
for file_path in files:
56-
global_line_counter = 1
57-
print_file(file_path, options)
36+
parser.add_argument("files", nargs="+", help="files to read")
37+
38+
args = parser.parse_args()
39+
40+
if args.number_nonblank:
41+
args.number_mode = "non-empty"
42+
elif args.number:
43+
args.number_mode = "all"
44+
else:
45+
args.number_mode = "none"
46+
47+
counter = 1
48+
for file in args.files:
49+
counter = print_file(file, args, counter)
5850

5951

6052
if __name__ == "__main__":

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

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,38 @@
11
#!/usr/bin/env python3
22
import sys
33
import os
4+
import argparse
45

5-
def list_directory(path, show_all, one_per_line):
6+
7+
def list_directory(path, show_all):
68
try:
79
entries = os.listdir(path)
8-
if show_all:
9-
# Add . and .. when -a is used
10-
entries = [".", ".."] + entries
11-
else:
12-
entries = [e for e in entries if not e.startswith(".")]
13-
14-
entries.sort(key=lambda x: (x not in (".", ".."), x))
15-
16-
for e in entries:
17-
print(e)
1810

1911
except Exception as e:
2012
print(f"Error reading directory {path}: {e}", file=sys.stderr)
2113
sys.exit(1)
14+
for entry in sorted(entries):
15+
if not show_all and entry.startswith("."):
16+
continue
17+
print(entry)
2218

2319

2420
def main():
25-
args = sys.argv[1:]
21+
parser = argparse.ArgumentParser(description="List directory contents")
22+
parser.add_argument("-a", "--all", action="store_true", help="show hidden files")
23+
parser.add_argument("paths", nargs="*", default=["."], help="directories to list")
2624

27-
show_all = "-a" in args
28-
one_per_line = "-1" in args
25+
args = parser.parse_args()
2926

30-
dirs = [a for a in args if a not in ("-a", "-1")]
31-
32-
if not dirs:
33-
dirs = [os.getcwd()]
27+
dirs = args.paths
3428

3529
for i, path in enumerate(dirs):
36-
if os.path.isdir(path):
37-
if len(dirs) > 1:
38-
print(f"{path}:")
39-
list_directory(path, show_all, one_per_line)
40-
if len(dirs) > 1 and i < len(dirs) - 1:
41-
print("")
42-
else:
43-
print(path)
30+
if len(dirs) > 1:
31+
print(f"{path}:")
32+
list_directory(path, args.all)
33+
34+
if len(dirs) > 1 and i < len(dirs) - 1:
35+
print("")
4436

4537

4638
if __name__ == "__main__":

0 commit comments

Comments
 (0)