roduprus

Terminal V1

Nov 15th, 2024 (edited)
29
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.09 KB | Source Code | 0 0
  1. import os
  2. import platform
  3. import subprocess
  4. import time
  5.  
  6. def clear_screen():
  7.     """Clears the command prompt screen based on the operating system."""
  8.     if platform.system() == "Windows":
  9.         os.system('cls')
  10.     else:
  11.         os.system('clear')
  12.  
  13. def close_explorer():
  14.     if platform.system() == "Windows":
  15.         try:
  16.             subprocess.run("taskkill /f /im explorer.exe", shell=True)
  17.             time.sleep(1)
  18.         except Exception:
  19.             pass
  20.     clear_screen()
  21.     print("Yo! This is a small project I work on when I'm bored.")
  22.     print("Exit using the [[exit]] command to recover explorer.exe")
  23.  
  24. def open_explorer():
  25.     if platform.system() == "Windows":
  26.         try:
  27.             subprocess.run("start explorer.exe", shell=True)
  28.         except Exception:
  29.             pass
  30.  
  31. def print_help():
  32.     """Prints a list of all available commands and how to use them."""
  33.     help_text = """
  34. Available commands:
  35.  create [[NAME]] [[FOLDER OR FILE]]  - Create a folder or file with the specified name.
  36.  rename [[OLD NAME]] [[NEW NAME]]    - Rename a file or folder.
  37.  changepath [[PATH]]                 - Change the current working directory to the specified path.
  38.  delete [[FILE NAME]]                - Delete the specified file.
  39.  edit [[FILE]] [[MODE]]              - Edit a file in one of three modes: overwrite, add, or rewrite.
  40.  read [[FILE]]                       - Read and display the contents of the specified file.
  41.  filecheck                           - List all files in the current directory with their sizes.
  42.  clear                               - Clear the screen.
  43.  exit                                - Exit the program.
  44.  help                                - Display this help message.
  45.  
  46. Edit modes for the 'edit' command:
  47.  overwrite - Completely replace the file's content.
  48.  add       - Append new content to the end of the file.
  49.  rewrite   - Modify specific lines within the file.
  50.  
  51. Examples:
  52.  create my_folder folder
  53.  create my_file.txt file
  54.  rename old_name.txt new_name.txt
  55.  changepath C:\\Users\\NewFolder
  56.  delete my_file.txt
  57.  edit my_file.txt overwrite
  58.  read my_file.txt
  59.  filecheck
  60.  clear
  61. """
  62.     print(help_text)
  63.  
  64. def main():
  65.     close_explorer()
  66.     base_directory = os.getcwd()
  67.     print(f"Current working directory: {base_directory}")
  68.  
  69.     while True:
  70.         command = input("\nEnter a command: ").strip()
  71.  
  72.         if command.lower() == "exit":
  73.             print("Exiting the program. Goodbye!")
  74.             break
  75.         elif command.lower() == "help":
  76.             print_help()
  77.         elif command.lower().startswith("create"):
  78.             parts = command.split()
  79.             if len(parts) == 3:
  80.                 name = parts[1]
  81.                 item_type = parts[2].lower()
  82.                 if item_type == "folder":
  83.                     try:
  84.                         os.makedirs(os.path.join(base_directory, name))
  85.                         print(f"Folder '{name}' created successfully.")
  86.                     except FileExistsError:
  87.                         print(f"Folder '{name}' already exists.")
  88.                     except Exception as e:
  89.                         print(f"Error creating folder '{name}': {e}")
  90.                 elif item_type == "file":
  91.                     try:
  92.                         file_path = os.path.join(base_directory, name)
  93.                         if not os.path.exists(file_path):
  94.                             with open(file_path, 'w') as file:
  95.                                 file.write('')
  96.                             print(f"File '{name}' created successfully.")
  97.                         else:
  98.                             print(f"File '{name}' already exists.")
  99.                     except Exception as e:
  100.                         print(f"Error creating file '{name}': {e}")
  101.                 else:
  102.                     print("Invalid type. Please specify 'folder' or 'file'.")
  103.             else:
  104.                 print("Invalid command format. Use: create [[NAME]] [[FOLDER OR FILE]]")
  105.  
  106.         elif command.lower().startswith("rename"):
  107.             parts = command.split(maxsplit=2)
  108.             if len(parts) == 3:
  109.                 old_name = parts[1]
  110.                 new_name = parts[2]
  111.  
  112.                 old_path = os.path.join(base_directory, old_name)
  113.                 new_path = os.path.join(base_directory, new_name)
  114.  
  115.                 if os.path.exists(old_path):
  116.                     try:
  117.                         os.rename(old_path, new_path)
  118.                         print(f"'{old_name}' has been renamed to '{new_name}'.")
  119.                     except Exception as e:
  120.                         print(f"Error renaming '{old_name}': {e}")
  121.                 else:
  122.                     print(f"The file or folder '{old_name}' does not exist.")
  123.             else:
  124.                 print("Invalid command format. Use: rename [[OLD NAME]] [[NEW NAME]]")
  125.  
  126.         elif command.lower().startswith("changepath"):
  127.             parts = command.split(maxsplit=1)
  128.             if len(parts) == 2:
  129.                 new_path = parts[1]
  130.  
  131.                 if os.path.isdir(new_path):
  132.                     base_directory = new_path
  133.                     print(f"Path changed to: {base_directory}")
  134.                 else:
  135.                     print(f"The path '{new_path}' does not exist or is not a directory.")
  136.             else:
  137.                 print("Invalid command format. Use: changepath [[PATH]]")
  138.  
  139.         elif command.lower().startswith("delete"):
  140.             parts = command.split(maxsplit=1)
  141.             if len(parts) == 2:
  142.                 file_name = parts[1]
  143.                 file_path = os.path.join(base_directory, file_name)
  144.  
  145.                 if os.path.isfile(file_path):
  146.                     try:
  147.                         os.remove(file_path)
  148.                         print(f"File '{file_name}' has been deleted.")
  149.                     except Exception as e:
  150.                         print(f"Error deleting file '{file_name}': {e}")
  151.                 else:
  152.                     print(f"The file '{file_name}' does not exist.")
  153.             else:
  154.                 print("Invalid command format. Use: delete [[FILE NAME]]")
  155.  
  156.         elif command.lower().startswith("edit"):
  157.             parts = command.split(maxsplit=2)
  158.             if len(parts) == 3:
  159.                 file_name = parts[1]
  160.                 mode = parts[2].lower()
  161.  
  162.                 file_path = os.path.join(base_directory, file_name)
  163.  
  164.                 if not os.path.isfile(file_path):
  165.                     print(f"The file '{file_name}' does not exist.")
  166.                     continue
  167.  
  168.                 if mode == "overwrite":
  169.                     try:
  170.                         print("Enter the new content. Type 'EOF' on a new line to finish.")
  171.                         with open(file_path, 'w') as file:
  172.                             while True:
  173.                                 line = input()
  174.                                 if line == "EOF":
  175.                                     break
  176.                                 file.write(line + '\n')
  177.                         print(f"File '{file_name}' has been overwritten successfully.")
  178.                     except Exception as e:
  179.                         print(f"Error overwriting file '{file_name}': {e}")
  180.  
  181.                 elif mode == "add":
  182.                     try:
  183.                         print("Enter the content to add. Type 'EOF' on a new line to finish.")
  184.                         with open(file_path, 'a') as file:
  185.                             while True:
  186.                                 line = input()
  187.                                 if line == "EOF":
  188.                                     break
  189.                                 file.write(line + '\n')
  190.                         print(f"Content has been added to '{file_name}' successfully.")
  191.                     except Exception as e:
  192.                         print(f"Error adding content to file '{file_name}': {e}")
  193.  
  194.                 elif mode == "rewrite":
  195.                     try:
  196.                         with open(file_path, 'r') as file:
  197.                             lines = file.readlines()
  198.  
  199.                         print("Current content of the file:")
  200.                         for i, line in enumerate(lines, start=1):
  201.                             print(f"{i}: {line.strip()}")
  202.  
  203.                         print("\nEnter new content for each line. Leave empty to keep the current line. Type 'EOF' when done.")
  204.                         with open(file_path, 'w') as file:
  205.                             for i, line in enumerate(lines, start=1):
  206.                                 new_line = input(f"Line {i}: ")
  207.                                 if new_line == "EOF":
  208.                                     file.write(line)
  209.                                     break
  210.                                 elif new_line.strip() == "":
  211.                                     file.write(line)
  212.                                 else:
  213.                                     file.write(new_line + '\n')
  214.                         print(f"File '{file_name}' has been rewritten successfully.")
  215.                     except Exception as e:
  216.                         print(f"Error rewriting file '{file_name}': {e}")
  217.  
  218.                 else:
  219.                     print("Invalid mode. Please use 'overwrite', 'add', or 'rewrite'.")
  220.             else:
  221.                 print("Invalid command format. Use: edit [[FILE]] [[MODE]]")
  222.  
  223.         elif command.lower().startswith("read"):
  224.             parts = command.split(maxsplit=1)
  225.             if len(parts) == 2:
  226.                 file_name = parts[1]
  227.  
  228.                 file_path = os.path.join(base_directory, file_name)
  229.  
  230.                 if os.path.isfile(file_path):
  231.                     try:
  232.                         with open(file_path, 'r') as file:
  233.                             content = file.read()
  234.                             print(f"Contents of '{file_name}':\n{content}")
  235.                     except Exception as e:
  236.                         print(f"Error reading file '{file_name}': {e}")
  237.                 else:
  238.                     print(f"The file '{file_name}' does not exist.")
  239.             else:
  240.                 print("Invalid command format. Use: read [[FILE]]")
  241.        
  242.         elif command.lower() == "filecheck":
  243.             try:
  244.                 files = [f for f in os.listdir(base_directory) if os.path.isfile(os.path.join(base_directory, f))]
  245.                 if files:
  246.                     print("Files in the current directory:")
  247.                     for file in files:
  248.                         size = os.path.getsize(os.path.join(base_directory, file))
  249.                         print(f"  - {file}: {size} bytes")
  250.                 else:
  251.                     print("No files found in the current directory.")
  252.             except Exception as e:
  253.                 print(f"Error checking files: {e}")
  254.  
  255.         elif command.lower() == "clear":
  256.             clear_screen()
  257.             print("Screen cleared. Please enter a new command.")
  258.             print(f"Current working directory: {base_directory}")
  259.  
  260.         else:
  261.             print(f"'{command}' is not recognized. Try again or type 'help' for a list of commands, or 'exit' to quit.")
  262.     open_explorer()
  263.  
  264. if __name__ == "__main__":
  265.     main()
Tags: terminal
Advertisement
Comments
  • roduprus
    321 days
    # text 0.12 KB | 0 0
    1. yes, yes i used chatgpt for some of this because i legit started tweaking when i started working on the [[edit]] command
Add Comment
Please, Sign In to add comment