Oto przykładowy skrypt w Pythonie, który spełnia Twoje wymagania: obsługuje subkomendy, umożliwia rozszerzanie przez pluginy, obsługuje autouzupełnianie w Oh-My-Zsh i pozwala na uruchamianie zadań w tle z widocznym wyjściem.
🔧 Struktura projektu
myapp/
│
├── main.py # Główny skrypt
├── plugins/ # Katalog z pluginami
│ ├── __init__.py
│ ├── ssh_connect.py # Przykładowy plugin
│ └── start_service.py # Inny przykład
│
└── completion.zsh # Skrypt autouzupełniania dla Oh-My-Zsh
📄 main.py
import argparse
import os
import importlib.util
import sys
import threading
import subprocess
import time
class CommandDispatcher:
def __init__(self):
self.commands = {}
def load_plugins(self, plugins_dir='plugins'):
for filename in os.listdir(plugins_dir):
if filename.endswith('.py') and not filename.startswith('__'):
module_name = filename[:-3]
module_path = os.path.join(plugins_dir, filename)
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if hasattr(module, 'run'):
self.commands[module_name] = module.run
def execute(self, command, *args):
if command in self.commands:
thread = threading.Thread(target=self.commands[command], args=args)
thread.start()
else:
print(f"Unknown command: {command}")
def main():
parser = argparse.ArgumentParser(description='My App with subcommands')
parser.add_argument('--complete', action='store_true', help='Output completion list')
parser.add_argument('command', nargs='?', help='Subcommand')
parser.add_argument('args', nargs=argparse.REMAINDER, help='Arguments for the subcommand')
args = parser.parse_args()
if args.complete:
dispatcher = CommandDispatcher()
dispatcher.load_plugins()
print('\n'.join(dispatcher.commands.keys()))
return
dispatcher = CommandDispatcher()
dispatcher.load_plugins()
if args.command:
dispatcher.execute(args.command, *args.args)
else:
parser.print_help()
if __name__ == '__main__':
main()
🧩 plugins/ssh_connect.py
import subprocess
import sys
import threading
def run(host, port=22):
def read_output(stream, is_stderr):
while True:
line = stream.readline()
if not line:
break
if is_stderr:
print(line, end='', file=sys.stderr)
else:
print(line, end='')
process = subprocess.Popen(
['ssh', f'root@{host}', '-p', str(port)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
stdout_thread = threading.Thread(target=read_output, args=(process.stdout, False))
stderr_thread = threading.Thread(target=read_output, args=(process.stderr, True))
stdout_thread.start()
stderr_thread.start()
# Nie czekaj na zakończenie procesu (fire-and-forget)
🧩 plugins/start_service.py
import subprocess
import sys
import threading
def run(service_name):
def read_output(stream, is_stderr):
while True:
line = stream.readline()
if not line:
break
if is_stderr:
print(line, end='', file=sys.stderr)
else:
print(line, end='')
process = subprocess.Popen(
['systemctl', 'start', service_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
stdout_thread = threading.Thread(target=read_output, args=(process.stdout, False))
stderr_thread = threading.Thread(target=read_output, args=(process.stderr, True))
stdout_thread.start()
stderr_thread.start()
# Nie czekaj na zakończenie procesu (fire-and-forget)
🧾 completion.zsh
# Compdef for myapp
_myapp() {
local -a commands
commands=($(myapp --complete))
_describe 'commands' commands
}
compdef _myapp myapp
✅ Jak używać
-
Instalacja autouzupełniania:
ln -s /ścieżka/do/myapp/completion.zsh ~/.oh-my-zsh/completions/_myapp
-
Dodawanie nowych pluginów:
- Utwórz nowy plik w katalogu
plugins/, np. plugins/my_plugin.py.
- W pliku zdefiniuj funkcję
run().
-
Uruchamianie subkomend:
myapp ssh_connect example.com
myapp start_service nginx
🔍 Dodatkowe funkcje
- Autouzupełnianie: Zostanie automatycznie zaimplementowane po dodaniu skryptu
completion.zsh do ~/.oh-my-zsh/completions/.
- Fire-and-forget: Subkomendy uruchamiają się w tle i nie blokują konsoli.
- Widoczne wyjście: Wyjście
stdout i stderr jest wyświetlane w czasie rzeczywistym.
🧪 Przykładowe wywołania
$ myapp ssh_connect 192.168.1.1 -p 2222
Connecting to 192.168.1.1...
Welcome to Ubuntu...
$ myapp start_service myservice
Starting myservice... [OK]
📌 Uwagi
- Dla bardziej zaawansowanych scenariuszy możesz dodać obsługę parametrów, logowania lub interfejsu graficznego.
- Możesz rozszerzyć skrypt o obsługę
--help dla każdej subkomendy.
Jeśli chcesz, mogę pomóc w dodaniu więcej funkcjonalności, np. logowania do pliku lub obsługa błędów.