Skip to content

Commit d72fc0a

Browse files
Enhance ls function with error handling and formatting
Added error handling for file access issues and improved output formatting.
1 parent 84dcfb7 commit d72fc0a

1 file changed

Lines changed: 21 additions & 5 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,46 @@
11
import os
2+
import sys
23
import argparse
34

45
def ls(path, one_column, show_hidden):
56
"""List files in a directory, optionally in one column or including hidden files."""
67
try:
8+
if os.path.isfile(path):
9+
print(os.path.basename(path))
10+
return
11+
712
files = os.listdir(path)
8-
if not show_hidden:
13+
14+
if show_hidden:
15+
files = ['.', '..'] + files
16+
else:
917
files = [f for f in files if not f.startswith('.')]
18+
1019
files.sort()
11-
20+
1221
if one_column:
1322
print(*files, sep='\n')
1423
else:
1524
print(*files)
25+
1626
except FileNotFoundError:
17-
print(f"ls: cannot access '{path}': No such file or directory")
27+
print(
28+
f"ls: cannot access '{path}': No such file or directory",
29+
file=sys.stderr
30+
)
1831
except NotADirectoryError:
19-
print(f"ls: cannot access '{path}': Not a directory")
32+
print(
33+
f"ls: cannot access '{path}': Not a directory",
34+
file=sys.stderr
35+
)
2036

2137
def main():
2238
parser = argparse.ArgumentParser()
2339
parser.add_argument('-1', dest='one_column', action='store_true', help='list one file per line')
2440
parser.add_argument('-a', action='store_true', help='show hidden files')
2541
parser.add_argument('path', nargs='?', default='.', help='directory to list')
2642
args = parser.parse_args()
27-
43+
2844
ls(args.path, args.one_column, args.a)
2945

3046
if __name__ == "__main__":

0 commit comments

Comments
 (0)