-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlang.py
69 lines (64 loc) · 2.22 KB
/
lang.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
60
61
62
63
64
65
66
67
68
69
import os
import sys
variables = {}
def rchop(string, suffix):
if suffix and string.endswith(suffix):
return string[:-len(suffix)]
return string
while True:
# debug
#print(variables)
try:
if not sys.argv[1] == "-c":
inp = input(">>").lstrip()
else:
inp = input().lstrip()
variable_assigned = False
# replace variable names with values
for var_name, var_value in variables.items():
inp = inp.replace(f"{var_name}$", var_value)
# variable handler
if ":=" in inp:
var_name, *var_value = inp.split(":=")
var_name, var_value = var_name.strip(), ':='.join(var_value)
if ' ' not in var_name and var_value:
variables[var_name] = var_value
variable_assigned = True
inp = inp or "No content"
keyword = inp.split(" ")[0]
# commands
if inp == "exit":
if not sys.argv[1] == "-c":
print("Exiting.")
break
elif keyword == "print":
print(inp[6:])
elif inp == "ls":
directories = [f for f in os.listdir('.') if not os.path.isfile(f)]
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for d in directories:
print(f'{d}/')
for f in files:
print(f)
elif keyword == "cd":
targetdirectory = inp[3:]
try:
os.chdir(targetdirectory)
if not sys.argv[1] == "-c":
print("Directory changed to %s" % os.getcwd())
except:
print(f'Unable to change directory to {targetdirectory}. Does the directory exist?')
elif inp.startswith("shell ") and inp.endswith(" shell"):
command = rchop(inp[6:], " shell")
os.system(command)
elif keyword == "pwd":
print(os.getcwd())
elif keyword == "calc":
expr = inp[5:]
print(expr, "=", eval(expr))
elif not variable_assigned:
print(f"syntax error - ({inp})")
except:
if not sys.argv[1] == "-c":
print("\nExiting.")
break