forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathls_v8.py
More file actions
52 lines (42 loc) · 1.19 KB
/
Copy pathls_v8.py
File metadata and controls
52 lines (42 loc) · 1.19 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
import argparse
import datetime
from pathlib import Path
parser = argparse.ArgumentParser(
prog="ls",
description="List the content of a directory",
epilog="Thanks for using %(prog)s! :)",
argument_default=argparse.SUPPRESS,
)
general = parser.add_argument_group("general output")
general.add_argument(
"path",
nargs="?",
default=".",
help="take the path to the target directory (default: %(default)s)",
)
detailed = parser.add_argument_group("detailed output")
detailed.add_argument(
"-l",
"--long",
action="store_true",
help="display detailed directory content",
)
args = parser.parse_args()
target_dir = Path(args.path)
if not target_dir.exists():
print("The target directory doesn't exist")
raise SystemExit(1)
def build_output(entry, long=False):
if long:
size = entry.stat().st_size
date = datetime.datetime.fromtimestamp(entry.stat().st_mtime).strftime(
"%b %d %H:%M:%S"
)
return f"{size:>6d} {date} {entry.name}"
return entry.name
for entry in target_dir.iterdir():
try:
long = args.long
except AttributeError:
long = False
print(build_output(entry, long=long))