|
6 | 6 |
|
7 | 7 |
|
8 | 8 | def list_directory(path, show_all): |
9 | | - """List contents of a directory, respecting the -a and -1 options.""" |
10 | | - |
11 | 9 | try: |
12 | | - entries = os.listdir(path) |
13 | | - except FileNotFoundError: |
14 | | - print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr) |
| 10 | + if os.path.isfile(path): |
| 11 | + # ls file.txt → just print the file name |
| 12 | + print(path) |
| 13 | + return |
| 14 | + |
| 15 | + if os.path.isdir(path): |
| 16 | + entries = os.listdir(path) |
| 17 | + else: |
| 18 | + print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr) |
| 19 | + return |
| 20 | + |
| 21 | + except PermissionError: |
| 22 | + print(f"ls: cannot open directory '{path}': Permission denied", file=sys.stderr) |
15 | 23 | return |
16 | 24 |
|
17 | 25 | # If -a is not provided, hide dotfiles |
18 | 26 | if not show_all: |
19 | 27 | entries = [e for e in entries if not e.startswith(".")] |
20 | 28 |
|
21 | | - # Sort alphabetically like ls normally does |
22 | 29 | entries.sort() |
23 | 30 |
|
24 | | - # Print one entry per line (-1 behaviour) |
25 | 31 | for entry in entries: |
26 | 32 | print(entry) |
27 | 33 |
|
28 | | - |
29 | 34 | def main(): |
30 | 35 | parser = argparse.ArgumentParser(description="Simple ls implementation") |
31 | 36 | parser.add_argument( |
32 | 37 | "-a", |
33 | 38 | action="store_true", |
34 | 39 | help="include directory entries whose names begin with a dot", |
35 | 40 | ) |
36 | | - parser.add_argument( |
37 | | - "-1", |
38 | | - dest="one_per_line", |
39 | | - action="store_true", |
40 | | - help="list one file per line", |
41 | | - ) |
| 41 | + |
42 | 42 | parser.add_argument("path", nargs="?", default=".", help="directory to list") |
43 | 43 |
|
44 | 44 | args = parser.parse_args() |
45 | 45 |
|
46 | | - # Only -1 is supported, but it's always required in this assignment |
47 | | - if not args.one_per_line: |
48 | | - print("This program only supports the -1 option.", file=sys.stderr) |
49 | | - sys.exit(1) |
50 | | - |
51 | 46 | list_directory(args.path, show_all=args.a) |
52 | 47 |
|
53 | | - |
54 | 48 | if __name__ == "__main__": |
55 | 49 | main() |
0 commit comments