/
pyminish
executable file
·67 lines (47 loc) · 1.41 KB
/
pyminish
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
67
#!/usr/bin/env python
import os
import sys
def builtin_echo(args):
print(" ".join(args))
def builtin_exit(args):
exit()
BUILTIN_COMMAND_FUNC_MAPPING = {
"echo": builtin_echo,
"exit": builtin_exit,
}
def find_command(command):
if "/" in command:
if os.path.exists(command):
return command
return None
for path in os.environ["PATH"].split(":"):
path = os.path.join(path, command)
if os.path.exists(path) and not os.path.isdir(path):
return path
return None
def main():
while True:
line = input("> ")
tokens = line.split()
if len(tokens) == 0:
continue
command = tokens[0]
args = tokens[1:]
if command in BUILTIN_COMMAND_FUNC_MAPPING:
func = BUILTIN_COMMAND_FUNC_MAPPING[command]
func(args)
else:
command_path = find_command(command)
if command_path is None:
print(f"{command}: command not found", file=sys.stderr)
continue
pid = os.fork()
if pid < 0:
print("fork failed", file=sys.stderr)
elif pid == 0:
command_basename = os.path.basename(command_path)
os.execve(command_path, [command_basename] + args, os.environ)
else:
os.waitpid(pid, 0)
if __name__ == "__main__":
main()