-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathls.py
More file actions
66 lines (52 loc) · 1.94 KB
/
ls.py
File metadata and controls
66 lines (52 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# implement-shell-tools/ls/ls.py
import argparse
import os
import sys
import shutil
import math
def print_columns(items, force_single_column=False):
"""Print items in columns unless -1 is passed or output is not a tty."""
if force_single_column or not sys.stdout.isatty():
for item in items:
print(item)
return
# Get terminal width
term_width = shutil.get_terminal_size((80, 20)).columns
if not items:
return
# Longest filename length + spacing
max_len = max(len(f) for f in items) + 2
cols = max(1, term_width // max_len)
rows = math.ceil(len(items) / cols)
for r in range(rows):
row_items = []
for c in range(cols):
i = c * rows + r
if i < len(items):
row_items.append(items[i].ljust(max_len))
print("".join(row_items).rstrip())
def main():
parser = argparse.ArgumentParser(
prog="ls",
description="Implements a simple version of the 'ls' command to list files in a directory."
)
parser.add_argument("-1", help="List one file per line", action="store_true")
parser.add_argument("-a", help="Include hidden files", action="store_true")
parser.add_argument("directory", nargs="?", default=".", help="The directory to search")
args = parser.parse_args()
try:
if os.path.isdir(args.directory):
files = os.listdir(args.directory)
if not args.a:
files = [f for f in files if not f.startswith(".")]
files = sorted(files)
print_columns(files, force_single_column=args.__dict__["1"])
else:
# If it's a file, just print the name
print(args.directory)
except FileNotFoundError:
print(f"ls: {args.directory}: No such file or directory", file=sys.stderr)
except Exception as e:
print(f"ls: {args.directory}: {e}", file=sys.stderr)
if __name__ == "__main__":
main()