#repl custom v1.11.0
#by DoThanhTung - Vietnam
#facebook my : https://facebook.com/xeolone
#email my : [email protected]
#Thank you for download
import time
time.sleep(0.1) # Wait for USB to become ready
import time
import os
import sys
def custom_repl():
print("Custom REPL with System Commands. Press Ctrl+C to exit!")
context = {} # Dictionary to store variables and functions in the context
history = [] # List to store command history
aliases = {} # Dictionary to store command aliases
def system_info():
"""Display basic system information."""
try:
fs_stat = os.statvfs("/")
total = fs_stat.f_frsize * fs_stat.f_blocks # Total storage
free = fs_stat.f_frsize * fs_stat.f_bfree # Free storage
print(f"Total storage: {total / 1024:.2f} KB")
print(f"Free storage: {free / 1024:.2f} KB")
except Exception as e:
print(f"Error getting system info: {e}")
def find_files(pattern):
"""Search for files matching a pattern in the current directory."""
try:
files = os.listdir()
matched_files = [file for file in files if file.endswith(pattern)]
if matched_files:
print("Found files:")
for file in matched_files:
print(f" {file}")
else:
print(f"No files found matching pattern '{pattern}'")
except Exception as e:
print(f"Error finding files: {e}")
def move_file(source, destination):
"""Move or rename a file."""
try:
os.rename(source, destination)
print(f"File '{source}' moved to '{destination}'.")
except Exception as e:
print(f"Error moving file: {e}")
def create_new_file(filename):
"""Create a new empty file."""
try:
with open(filename, "w") as file:
pass # Just create an empty file
print(f"New file '{filename}' created.")
except Exception as e:
print(f"Error creating file: {e}")
def write_to_file(filename, content):
"""Write multiline content to a file."""
try:
with open(filename, "w") as file:
file.write(content)
print(f"Content written to '{filename}'.")
except Exception as e:
print(f"Error writing to file {filename}: {e}")
def run_script(filename):
"""Run a Python script from the system."""
try:
with open(filename, "r") as file:
script = file.read()
exec(script, context) # Execute the script in the REPL context
print(f"Successfully executed script '{filename}'.")
except OSError:
print(f"Error: File '{filename}' not found.")
except Exception as e:
print(f"Error running script {filename}: {type(e).__name__}: {e}")
def multiline_input():
"""Handle multiline input until !end is typed."""
print("Entering multiline mode. Type !end to finish.")
lines = []
while True:
try:
line = input("... ")
if line.strip() == "!end":
break
lines.append(line)
except EOFError:
break # End input on EOF (Ctrl+D)
return "\n".join(lines) # Return multiline input
while True:
try:
cmd = input("Custom REPL> ").strip()
# Skip empty commands
if not cmd:
continue
# Add the command to history
history.append(cmd)
# Handle special commands
if cmd == "!help":
print("""
Special commands:
!help - Show help
!ls - List files in the current directory
!cat <file> - Display the content of a file
!rm <file> - Delete a file
!sysinfo - Show system storage info
!find <pattern> - Find files matching a pattern (e.g., .txt)
!mv <source> <destination> - Move or rename a file
!touch <filename> - Create a new empty file
!write <filename> - Write multiline content to a file
!run <filename> - Run a Python script from the system
!alias short="long command" - Set an alias for a command
!unalias <alias> - Delete an alias
!list_alias - List all defined aliases
!time <command> - Measure the execution time of a command
!repeat <n> <command> - Repeat a command n times
!multiline - Enter multiline input to execute
""")
elif cmd == "!ls":
try:
files = os.listdir()
print("Files in the current directory:")
for file in files:
print(f" {file}")
except Exception as e:
print(f"Error listing files: {type(e).__name__}: {e}")
elif cmd.startswith("!cat "):
try:
_, filename = cmd.split(" ", 1)
with open(filename, "r") as file:
content = file.read()
print(content)
except Exception as e:
print(f"Error reading file {filename}: {type(e).__name__}: {e}")
elif cmd == "!multiline":
try:
code = multiline_input()
compiled_code = compile(code, "<multiline_input>", "exec")
exec(compiled_code, context)
except Exception as e:
print(f"Error executing multiline code: {e}")
elif cmd.startswith("!rm "):
try:
_, filename = cmd.split(" ", 1)
os.remove(filename)
print(f"File {filename} deleted.")
except Exception as e:
print(f"Error deleting file {filename}: {type(e).__name__}: {e}")
elif cmd == "!sysinfo":
system_info()
elif cmd.startswith("!find "):
_, pattern = cmd.split(" ", 1)
find_files(pattern)
elif cmd.startswith("!mv "):
try:
_, source, destination = cmd.split(" ", 2)
move_file(source, destination)
except ValueError:
print("Invalid syntax! Use: !mv <source> <destination>")
elif cmd.startswith("!touch "):
try:
_, filename = cmd.split(" ", 1)
create_new_file(filename)
except ValueError:
print("Invalid syntax! Use: !touch <filename>")
elif cmd.startswith("!write "):
try:
_, filename = cmd.split(" ", 1)
content = multiline_input()
write_to_file(filename, content)
except Exception as e:
print(f"Error writing to file: {e}")
elif cmd.startswith("!run "):
try:
_, filename = cmd.split(" ", 1)
run_script(filename)
except ValueError:
print("Invalid syntax! Use: !run <filename>")
elif cmd.startswith("!alias "):
try:
alias, full_cmd = cmd[7:].split("=")
full_cmd = full_cmd.strip().strip('"').strip("'")
aliases[alias.strip()] = full_cmd
print(f"Alias '{alias.strip()}' set to '{full_cmd}'.")
except ValueError:
print("Invalid syntax! Use: !alias short=\"long command\"")
elif cmd.startswith("!unalias "):
alias_to_remove = cmd[9:].strip()
if alias_to_remove in aliases:
del aliases[alias_to_remove]
print(f"Alias '{alias_to_remove}' removed.")
else:
print(f"Alias '{alias_to_remove}' does not exist.")
elif cmd == "!list_alias":
if aliases:
print("Defined aliases:")
for alias, command in aliases.items():
print(f" {alias} -> {command}")
else:
print("No aliases defined.")
elif cmd.startswith("!time "):
user_cmd = cmd[6:]
start_time = time.time()
try:
exec(user_cmd, context)
except Exception as e:
print(f"Error while executing the command: {e}")
end_time = time.time()
print(f"Execution time: {end_time - start_time:.6f} seconds")
elif cmd.startswith("!repeat "):
try:
_, repeat_count, user_cmd = cmd.split(" ", 2)
repeat_count = int(repeat_count)
for i in range(repeat_count):
print(f"Execution {i + 1}:")
exec(user_cmd, context)
except Exception as e:
print(f"Error: {e}")
elif cmd in aliases:
exec(aliases[cmd], context)
else:
try:
result = eval(cmd, context)
if result is not None:
print(repr(result))
except SyntaxError:
try:
exec(cmd, context)
except Exception as e:
print(f"Execution Error: {type(e).__name__}: {e}")
except Exception as e:
print(f"General Error: {type(e).__name__}: {e}")
except KeyboardInterrupt:
print("\nExiting REPL.")
break
custom_repl()