Chce napisac aplikacje w python, ktora zgromadzi kilka "subfunkcji". Subfunkcje to beda…
- User
Chce napisac aplikacje w python, ktora zgromadzi kilka "subfunkcji". Subfunkcje to beda subkomendy (z ewentualnymi parametrami), ktore beda odpalaly rozne funkcjonalnosci.
Napisz taki skrypt, ktory w latwy sposob bede mogl rozwijac (dodac nowe subkomendy). Najlepiej, jezeli bedzie mozliwa obsluga pluginow. Chce, zeby oh-my-zsh uzupelnialo skladnie sub-komend.
Sub-komendy beda odpalaly niektore aplikacje w watkach, ktore beda konczyly sie polaczeniem SSH. Czyli chce miec na koniec pozostawiona konsole do dalszych dzialan. Ale niektore komendy to bedzie cos w stylu fire&forget. Chcialbym jedynie widziec rezultat komendy (stdout/stderr etc)
Assistant
Poniżej przedstawiam przykładowy skrypt Python, który spełnia Twoje wymagania. Skrypt ten jest modułowy, obsługuje subkomendy, pozwala na dodawanie nowych funkcjonalności (w tym pluginów), oraz obsługuje uruchamianie procesów w wątkach z opcją interakcji przez SSH lub tryb "fire-and-forget".
Struktura projektu:
my_app/ │ ├── main.py ├── commands/ │ ├── __init__.py │ ├── ssh_command.py │ ├── fire_and_forget.py │ └── ... (inne komendy) ├── plugins/ │ └── __init__.py └── utils/ ├── __init__.py ├── thread_utils.py └── ssh_utils.pymain.pyimport argparse import importlib import os import sys from threading import Thread from utils.thread_utils import run_in_thread from utils.ssh_utils import ssh_connect class MyApp: def __init__(self): self.commands = {} self.load_commands() self.load_plugins() def load_commands(self): commands_dir = os.path.join(os.path.dirname(__file__), 'commands') for filename in os.listdir(commands_dir): if filename.endswith('.py') and filename != '__init__.py': module_name = filename[:-3] module = importlib.import_module(f'commands.{module_name}') command_class = getattr(module, f'{module_name.capitalize()}Command') self.commands[module_name] = command_class() def load_plugins(self): plugins_dir = os.path.join(os.path.dirname(__file__), 'plugins') for filename in os.listdir(plugins_dir): if filename.endswith('.py') and filename != '__init__.py': module_name = filename[:-3] importlib.import_module(f'plugins.{module_name}') def run(self): parser = argparse.ArgumentParser(prog='my_app') subparsers = parser.add_subparsers(dest='command') for command_name, command_class in self.commands.items(): subparser = subparsers.add_parser(command_name, help=command_class.help()) command_class.add_arguments(subparser) args = parser.parse_args() if args.command: command_class = self.commands[args.command] command_class.run(args) else: parser.print_help() if __name__ == '__main__': app = MyApp() app.run()commands/ssh_command.pyimport argparse from utils.ssh_utils import ssh_connect class SshCommand: @staticmethod def help(): return "Connect to a remote server via SSH" @staticmethod def add_arguments(parser): parser.add_argument('host', help='Remote host to connect to') parser.add_argument('-u', '--user', help='Username for SSH connection', default='user') parser.add_argument('-p', '--port', type=int, help='SSH port', default=22) @staticmethod def run(args): ssh_connect(args.host, args.user, args.port)commands/fire_and_forget.pyimport argparse import subprocess from utils.thread_utils import run_in_thread class FireAndForgetCommand: @staticmethod def help(): return "Run a command in fire-and-forget mode" @staticmethod def add_arguments(parser): parser.add_argument('command', help='Command to run') @staticmethod def run(args): process = subprocess.Popen(args.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() print(f"Stdout: {stdout.decode()}") print(f"Stderr: {stderr.decode()}")utils/thread_utils.pyimport threading def run_in_thread(target, *args, **kwargs): thread = threading.Thread(target=target, args=args, kwargs=kwargs) thread.start() return threadutils/ssh_utils.pyimport paramiko def ssh_connect(host, user, port): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, port=port, username=user) # Uruchom interaktywną sesję SSH transport = client.get_transport() channel = transport.open_session() channel.get_pty() channel.invoke_shell() # Przekieruj wejście/wyjście do terminala import sys import select import shutil while True: if channel.exit_status_ready(): break r, w, e = select.select([channel, sys.stdin], [], []) if channel in r: try: x = channel.recv(1024) if len(x) == 0: sys.stdout.write('\r\n*** EOF\r\n') break sys.stdout.write(x.decode()) sys.stdout.flush() except Exception as e: print(e) break if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break channel.send(x) channel.close() client.close()Obsługa pluginów:
W katalogu
plugins/możesz dodawać nowe pliki Python, które będą automatycznie ładowane. Na przykład:# plugins/example_plugin.py from commands.ssh_command import SshCommand class ExtendedSshCommand(SshCommand): @staticmethod def help(): return "Extended SSH command with additional features" @staticmethod def add_arguments(parser): super().add_arguments(parser) parser.add_argument('--extra', help='Extra option for extended SSH command') @staticmethod def run(args): print(f"Extra option: {args.extra}") super().run(args) # Zastąp oryginalną komendę SSH rozszerzoną wersją from main import MyApp MyApp.commands['ssh'] = ExtendedSshCommand()Uzupełnianie składni w oh-my-zsh:
Utwórz plik
_my_appw katalogufunctionsoh-my-zsh:#compdef my_app local -a subcommands subcommands=( 'ssh:Connect to a remote server via SSH' 'fire-and-forget:Run a command in fire-and-forget mode' # Dodaj tutaj kolejne subkomendy ) _describe 'my_app commands' subcommandsDodaj następujące linie do pliku
.zshrc:fpath=(~/.oh-my-zsh/custom/functions $fpath) autoload -U compinit compinitRozszerzalność:
- Nowe komendy: Dodaj nowy plik w katalogu
commands/, zaimplementuj klasę z metodamihelp(),add_arguments(), irun(). - Pluginy: Dodaj nowy plik w katalogu
plugins/, który może modyfikować istniejące komendy lub dodawać nowe.
Ten skrypt zapewnia elastyczną strukturę, która pozwala na łatwe dodawanie nowych funkcjonalności i obsługę pluginów.
- Nowe komendy: Dodaj nowy plik w katalogu
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.