-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
59 lines (44 loc) · 1.3 KB
/
main.py
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
import os
import sys
import subprocess
from pathlib import Path
sys_clear_cmd = "cls" if os.name == "nt" else "clear"
def reset(cwd: str, new_line = True):
if new_line:
print()
main(cwd)
def main(cwd: str):
print(cwd)
cmd = input("> ").strip()
cmd_parts = cmd.split()
match cmd_parts[0]:
case "cd":
args = cmd_parts[1:]
if len(args) == 0:
cwd = str(Path("~").expanduser())
else:
os.chdir(args[0])
# we want os.getcwd(), which is absolute. args[0] is relative.
cwd = os.getcwd()
reset(cwd)
return
case "exit":
sys.exit(0)
try:
result = subprocess.run(
cmd_parts,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=cwd
)
if result.stdout:
print(result.stdout, end="")
if result.stderr:
print(result.stderr, end="", file=sys.stderr)
except Exception as e:
print(e, file=sys.stderr)
reset(cwd, new_line=cmd != sys_clear_cmd)
if __name__ == "__main__":
print("welcome to mini-shell!\n")
main(os.getcwd())