Задать вопрос
UMFUCHI
@UMFUCHI
НедоПайтонист

Как закрыть браузер желательно с помощью библиотеки os?

Смотрите, есть код который открывает приложение:
@vcl.on('открой оперу')
def start_opera(text):
    open_opera()
    return "Браузер запущен"

def open_opera():
    os.startfile('C:/Users/User/AppData/Local/Programs/Opera GX/launcher.exe')

Как сделать чтобы при команде "закрой оперу", оно закрывало браузер?

Вот весь код

import pyautogui
import os
from gtts import gTTS
import random
import time
import datetime
import playsound
import speech_recognition as sr
import pyautogui as pg


def listen_command():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Скажите вашу команду: ")
        audio = r.listen(source)

    try:
        our_speech = r.recognize_google(audio, language="ru")
        print("Вы сказали: " + our_speech)
        return our_speech
    except sr.UnknownValueError:
        return "ошибка"
    except sr.RequestError:
        return "ошибка"


class VoiceCommandList:
    def __init__(self):
        self.actions = list()

    def on(self, condition):
        if isinstance(condition, list):
            conditions = [el.lower() for el in condition]
            predicate = lambda text: any(condition in text for condition in conditions)
        elif isinstance(condition, str):
            condition = condition.lower()
            predicate = lambda text: condition in text

        if isinstance(condition, str):
            condition = condition.lower()
            predicate = lambda text: condition in text
        elif callable(condition):
            predicate = condition
        else:
            raise TypeError('Condition must be either string or function!')

        def decorator(command_func):
            self.actions.append((predicate, command_func))
            return command_func

        return decorator

    def run_command(self, text):
        text = text.lower()
        for predicate, command in self.actions:
            if predicate(text):
                try:
                    response = command(text)
                    if response is None:
                        response = "Команда выполнена"
                except Exception as err:
                    response = "Ошибка при выполнении команды"
                    print(err)
                if response:
                    say_message(response)
                break
        else:
            say_message("Неизвестная команда")
vcl = VoiceCommandList()

@vcl.on('открой оперу')
def start_opera(text):
    open_opera()
    return "Браузер запущен"

@vcl.on('закрой оперу')
def close_opera(text):
    close_browser()
    return "Браузер закрыт"

def open_opera():
    os.startfile('C:/Users/User/AppData/Local/Programs/Opera GX/launcher.exe')

def close_browser():
     print('здесь пока ничего нет')

def say_message(message):
    voice = gTTS(message, lang="ru")
    file_voice_name = "_audio_" + str(time.time()) + "_" + str(random.randint(0, 100000)) + ".mp3"
    voice.save(file_voice_name)
    playsound.playsound(file_voice_name)
    print("Голосовой ассистент: " + message)


if __name__ == '__main__':
    while True:
        command = listen_command()
        vcl.run_command(command)


И прошу расписать код так чтобы было понятно даже для меня(чайника)
  • Вопрос задан
  • 170 просмотров
Подписаться 2 Простой Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
от 200 000 до 300 000 ₽
Greenway Global Новосибирск
от 150 000 ₽
Akronix Санкт-Петербург
от 150 000 до 200 000 ₽
02 февр. 2025, в 12:33
3000 руб./за проект
02 февр. 2025, в 12:27
5000 руб./за проект
02 февр. 2025, в 11:35
3000 руб./за проект