This is the code for Pylect, a Python terminal I worked on a while ago which also caused my Desktop to get destroyed because of bad code. I use it infrequently but I would like a review for the code since this is a bit larger project that has span multiple months so there is some unclear bad code hidden in there likely.
Pylect is a REPL in which you provide Python code and Pylect executes the code and so on.
You can pass flags which are:
--name | Changes the name of the terminal.
--modules | Imports the comma-separated list of modules.
--dev | Shows debugging messages.
There are custom commands that Pylect has beginning with .:
.imports | Shows the imported modules.
.history | Shows the history so far.
.history prev | Shows the last item in the history.
.exit-env | Exits Pylect.
.clear-env | Clears all files in the Pylect folder except the Python files needed for Pylect.
There are also other things for fun (import ., import cake, import thanks, raise PylectError). 0.1+0.2 prints 0.3 is there because Python itself does the calculation wrong and there's also a reminder when I forgot the . before exit-env.
There is also a security feature where it has you type a password to access Pylect if there is a password. You can create a password, edit the password, and even remove the password through another program.
There is a configuration program for switching Pylect versions easily.
All text files involved:
.pylect.password.txt - Has the password.
.pylect.aliasversion.txt - Has the version which will be aliased to assuming that the .zprofile actually uses it for aliasing of course.
~/pylect/pylect1.1/.pylect.py
try:
import getpass
pw = open("/Users/jfami/pylect/.pylect.password.txt", "r").read()
gpw = getpass.getpass(prompt="Password: ")
if str(gpw) == str(pw):
invalid = False
pass
else:
print("Invalid password")
invalid = True
except:
invalid = False
pass
if invalid == True:
quit()
import sys, os, platform
from os import system as shell
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
if "--dev" in sys.argv:
dev = True
else:
dev = False
if "--name" in sys.argv:
try:
if dev: print(f"[Pylect] name = {sys.argv[sys.argv.index('--name')+1]}")
name = sys.argv[sys.argv.index("--name")+1]
except:
if dev:
print("[Pylect] name could not be initalized, choosing default name")
print('[Pylect] name = "Pylect"')
name = "Pylect"
else:
if dev: print(f'[Pylect] name = "Pylect"')
name = "Pylect"
if "--modules" in sys.argv:
try:
modules = sys.argv[sys.argv.index("--modules")+1]
modules = modules.split(",")
except:
if dev:
print("[Pylect] modules could not be initalized, ignoring option")
modules = []
else:
modules = []
class Pylect():
def __init__(self):
self.name = "Pylect"
self.env_folder = "pylect1.1"
self.version_tuple = (1, 1, 6)
self.version_status = "release"
self.version = "1.1.6"
self.build = 49
self.src = "python"
self.src_path = "/Users/jfami/pylect/pylect1.1"
self.modules = allmodules
self.__pylect__ = self
del __file__
sys.pylect = Pylect()
sys.exec_context = (os.getcwd(), (platform.system(), platform.release()), (platform.uname().machine, platform.uname().node), (platform.python_implementation(), platform.python_compiler(), platform.python_build()), (sys.pylect.name, sys.pylect.env, sys.pylect.version))
sys.env = ("3.11", "pylect1.1")
sys.filename = ""
sys.validargs = ["--dev", "--name", "--modules"]
sys.pylectargs = []
sys.invalidargs = False
sys.ispylect = True
sys.argv.remove(sys.argv[0])
for arg in sys.argv:
if arg.startswith("--"):
sys.pylectargs.append(arg)
if not arg == "--dev":
try:
if sys.argv[sys.argv.index(arg)+1].startswith("--"): raise Exception
sys.pylectargs.append(sys.argv[sys.argv.index(arg)+1])
sys.argv.remove(sys.argv[sys.argv.index(arg)+1])
except:
sys.invalidargs = True
sys.argv.remove(arg)
if dev and sys.invalidargs: print("Some args could not be initalized")
print(f"{name} Terminal!")
def exit_env():
from os import walk, remove
from os.path import join
path = '/Users/jfami/pylect/pylect1.1'
items = [join(root, file) for root, subdirs, files in walk(path) for file in files]
if len(items) == 1: return
for item in items:
if "pylect.py" in item:
pass
else:
remove(item)
cmds = []
while True:
if modules != []:
for module in modules:
if dev: print(f"[Pylect] import {module}")
try:
exec(f"import {module}", globals(), locals())
except:
print(f"No module named '{module}'")
inp = input("> ")
if dev and not inp[0] == ".": print(f"[Pylect] {inp}")
cmds.append(inp)
if inp == ".imports":
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
print(allmodules)
continue
elif inp == ".env":
import sys
print(f"Python {sys.version.split(' ')[0]} (pylect1.1)")
continue
elif inp == ".exit-env":
if dev: print("[Pylect] exit_env()")
if dev: print("[Pylect] exit()")
exit_env()
exit()
elif inp == ".clear-env":
if dev: print("[Pylect] exit_env()")
exit_env()
continue
elif inp == ".history":
if dev: print("[Pylect] cmds")
print(cmds)
continue
elif inp == ".history prev":
if dev: print("[Pylect] cmds[-2]")
print(cmds[-2])
continue
elif inp == "import .":
print("This is not a module :)")
continue
elif inp == "import cake":
print("THE CAKE IS A LIE!")
continue
elif inp == "import thanks":
print("Thank you")
continue
elif inp == "0.1+0.2":
print(0.3)
continue
elif inp == "raise PylectError":
print("PylectError: Could not find `PylectError`")
continue
elif inp == "exit-env":
print("You forgot a dot.")
continue
try:
res = eval(inp, globals(), locals())
print(res)
except KeyboardInterrupt:
exit_env()
exit()
except:
try:
exec(inp, globals(), locals())
except Exception as e:
print(str(e))
~/pylect/pylect1.1/.pylect.password.py
import os
if os.path.exists("/Users/jfami/pylect/.pylect.password.txt"):
change = input("Do you want to change your password? (y/n) ")
if change == "y":
with open("/Users/jfami/pylect/.pylect.password.txt", "w") as pw:
password = input("Input your new password: ")
pw.write(password)
else:
remove = input("Do you want to remove your password? (NOT RECOMMENDED) (y/n) ")
if remove == "y":
os.remove("/Users/jfami/pylect/.pylect.password.txt")
else:
setup = input("Setup a Pylect password? (y/n) ")
if setup == "y":
with open("/Users/jfami/pylect/.pylect.password.txt", "w") as pw:
password = input("Input your password: ")
pw.write(password)
~/pylect/pylect1.1/.pylect.config.py
import os
import subprocess
import sys
if sys.argv[1] == "list" or sys.argv[1] == "-l":
print("Pylect: Finding avaliable versions...")
versions = [x.split("pylect")[1] for x in subprocess.check_output("ls ~/pylect", shell=True).decode().strip().split("\n")]
for version in versions:
if open("~/pylect/.pylect.aliasversion.txt", "r").read().strip() == version:
print(version, "(current)")
else:
print(version)
elif sys.argv[1] == "version" or sys.argv[1] == "-v":
print(f"Pylect {open("~/pylect/.pylect.aliasversion.txt", "r").read().strip()} (pylect{open("~/pylect/.pylect.aliasversion.txt", "r").read().strip()})")
elif sys.argv[1] == "run" or sys.argv[1] == "-r":
args = ""
for arg in sys.argv[1:]:
args += f" {arg}"
os.system(f"pylect {args}")
elif inp == "0.1+0.2":
seem to be nothing more than a meme so make understanding what is and isn't important hard. \$\endgroup\$