def execute_command_interactive(self, command: str, timeout: int) -> Tuple[str, str, int]:
"""Выполняет команду с интерактивным мониторингом"""
print(f"\n🔄 Запуск интерактивной команды с мониторингом каждые {self.MONITORING_INTERVAL} секунд")
code
runner = InteractiveCommandRunner(command, timeout)
if not runner.start_process():
return "", "Не удалось запустить процесс", 1
print(f"🆕 Команда: {command}")
print(f"🔢 PID процесса: {runner.process.pid}")
print(f"⏱️ Максимальный таймаут: {timeout}с")
print("=" * 60)
try:
while runner.is_running():
wait_time = 0
while wait_time < self.MONITORING_INTERVAL and runner.is_running():
time.sleep(1)
wait_time += 1
print(f"\n⏳ Прошло {wait_time} секунд...")
if not runner.is_running():
print("✅ Процесс завершён.")
break
output = runner.get_current_output()
if output['new_stdout'] or output['new_stderr'] or runner.should_check_with_ai():
print(f"\n📊 Промежуточный вывод (время работы: {output['running_time']:.1f}с)")
print("-" * 50)
if output['new_stdout']:
print(f"📤 Новый STDOUT:\n{output['new_stdout']}")
if output['new_stderr']:
print(f"📤 Новый STDERR:\n{output['new_stderr']}")
if not output['new_stdout'] and not output['new_stderr']:
print("ℹ️ Нет нового вывода.")
print("\n🧠 Обращение к AI за решением...")
ai_action = self.ask_ai_for_interaction(command, output)
if ai_action:
print("✅ Ответ от AI:")
print(json.dumps(ai_action, indent=2, ensure_ascii=False))
action_type = ai_action.get('action', 'continue')
if action_type == 'send_input':
input_text = ai_action.get('input', '')
print(f"⌨️ AI отправляет ввод в stdin: {input_text!r}")
runner.send_input(input_text)
elif action_type == 'interrupt':
print("🛑 AI решил прервать выполнение команды.")
runner.interrupt_process()
break
elif action_type == 'continue':
print("🔁 AI рекомендует продолжить ожидание.")
else:
print("⚠️ AI не дал осмысленного ответа. Продолжаем.")
runner.mark_checked()
else:
print("📭 Нет изменений и не пришло время AI-проверки.")
if output['running_time'] > timeout:
print(f"\n⏰ ВРЕМЯ ВЫШЛО! Таймаут {timeout}с превышен — прерываем процесс.")
runner.interrupt_process()
break
except KeyboardInterrupt:
print("\n🛑 Процесс прерван пользователем.")
runner.interrupt_process()
print("\n📥 Получаем финальный результат процесса...")
time.sleep(1)
return runner.get_final_result() напеши с отступами как в классе
def execute_command_interactive(self, command: str, timeout: int) -> Tuple[str, str, int]:
"""Выполняет команду с интерактивным мониторингом"""
print(f"\n🔄 Запуск интерактивной команды с мониторингом каждые {self.MONITORING_INTERVAL} секунд")
runner = InteractiveCommandRunner(command, timeout)
if not runner.start_process():
return "", "Не удалось запустить процесс", 1
print(f"🆕 Команда: {command}")
print(f"🔢 PID процесса: {runner.process.pid}")
print(f"⏱️ Максимальный таймаут: {timeout}с")
print("=" * 60)
try:
while runner.is_running():
wait_time = 0
while wait_time < self.MONITORING_INTERVAL and runner.is_running():
time.sleep(1)
wait_time += 1
print(f"\n⏳ Прошло {wait_time} секунд...")
if not runner.is_running():
print("✅ Процесс завершён.")
break
output = runner.get_current_output()
if output['new_stdout'] or output['new_stderr'] or runner.should_check_with_ai():
print(f"\n📊 Промежуточный вывод (время работы: {output['running_time']:.1f}с)")
print("-" * 50)
if output['new_stdout']:
print(f"📤 Новый STDOUT:\n{output['new_stdout']}")
if output['new_stderr']:
print(f"📤 Новый STDERR:\n{output['new_stderr']}")
if not output['new_stdout'] and not output['new_stderr']:
print("ℹ️ Нет нового вывода.")
print("\n🧠 Обращение к AI за решением...")
ai_action = self.ask_ai_for_interaction(command, output)
if ai_action:
print("✅ Ответ от AI:")
print(json.dumps(ai_action, indent=2, ensure_ascii=False))
action_type = ai_action.get('action', 'continue')
if action_type == 'send_input':
input_text = ai_action.get('input', '')
print(f"⌨️ AI отправляет ввод в stdin: {input_text!r}")
runner.send_input(input_text)
elif action_type == 'interrupt':
print("🛑 AI решил прервать выполнение команды.")
runner.interrupt_process()
break
elif action_type == 'continue':
print("🔁 AI рекомендует продолжить ожидание.")
else:
print("⚠️ AI не дал осмысленного ответа. Продолжаем.")
runner.mark_checked()
else:
print("📭 Нет изменений и не пришло время AI-проверки.")
if output['running_time'] > timeout:
print(f"\n⏰ ВРЕМЯ ВЫШЛО! Таймаут {timeout}с превышен — прерываем процесс.")
runner.interrupt_process()
break
except KeyboardInterrupt:
print("\n🛑 Процесс прерван пользователем.")
runner.interrupt_process()
print("\n📥 Получаем финальный результат процесса...")
time.sleep(1)
return runner.get_final_result()
Этот код представляет собой метод класса, который выполняет команду с интерактивным мониторингом. Он создаёт объект InteractiveCommandRunner, запускает процесс и мониторит его выполнение, периодически проверяя вывод и обращаясь к AI за решениями. В случае превышения таймаута или прерывания пользователем, процесс завершается. В конце возвращается финальный результат выполнения команды.