Многопроцессорная обработка с сигнализацией - PullRequest
2 голосов
/ 23 октября 2019

Я давно работаю над личным помощником в python и столкнулся с проблемой, которую не могу решить.

Я хочу добавить напоминание.

Я хочу объединить код тревоги и код помощника в двух разных циклах .

Когда я устанавливаю таймер будильника, я хочу выполнять другие входные задачи, пока таймер не истечет.

Как я могу это сделать? Спасибо.

Я пробовал этот код, но он не работает, потому что у меня есть только один цикл:

import datetime
import os
import time
import random

def assistant():
    command = input('command: ')
    if command == '1':
        print('is it one')
    elif command == '2':
        print('is it two')
    elif command == 'alarm':
        import datetime

        def check_alarm_input(alarm_time):
            if len(alarm_time) == 1: # [Hour] Format
                if alarm_time[0] < 24 and alarm_time[0] >= 0:
                    return True
            if len(alarm_time) == 2: # [Hour:Minute] Format
                if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
                    alarm_time[1] < 60 and alarm_time[1] >= 0:
                    return True
            elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
                if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
                    alarm_time[1] < 60 and alarm_time[1] >= 0 and \
                    alarm_time[2] < 60 and alarm_time[2] >= 0:
                    return True
            return False

        # Get user input for the alarm time
        print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")

        while True:
            alarm_input = input(">> ")
            try:
                alarm_time = [int(n) for n in alarm_input.split(":")]
                if check_alarm_input(alarm_time):
                    break
                else:
                    raise ValueError
            except ValueError:
                print("ERROR: Enter time in HH:MM or HH:MM:SS format")

        # Convert the alarm time from [H:M] or [H:M:S] to seconds
        seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
        alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])

        # Get the current time of day in seconds
        now = datetime.datetime.now()
        current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])

        # Calculate the number of seconds until alarm goes off
        time_diff_seconds = alarm_seconds - current_time_seconds

        # If time difference is negative, set alarm for next day
        if time_diff_seconds < 0:
            time_diff_seconds += 86400 # number of seconds in a day

        # Display the amount of time until the alarm goes off
        print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))

        # Sleep until the alarm goes off
        time.sleep(time_diff_seconds)

        # Time for the alarm to go off
        print("Wake Up!")

while True:
    assistant()

1. Код напоминания:

import datetime
import os
import time
import random

def check_alarm_input(alarm_time):
    """Checks to see if the user has entered in a valid alarm time"""
    if len(alarm_time) == 1: # [Hour] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0:
            return True
    if len(alarm_time) == 2: # [Hour:Minute] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
           alarm_time[1] < 60 and alarm_time[1] >= 0:
            return True
    elif len(alarm_time) == 3: # [Hour:Minute:Second] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
           alarm_time[1] < 60 and alarm_time[1] >= 0 and \
           alarm_time[2] < 60 and alarm_time[2] >= 0:
            return True
    return False

# Get user input for the alarm time
print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
while True:
    alarm_input = input(">> ")
    try:
        alarm_time = [int(n) for n in alarm_input.split(":")]
        if check_alarm_input(alarm_time):
            break
        else:
            raise ValueError
    except ValueError:
        print("ERROR: Enter time in HH:MM or HH:MM:SS format")

# Convert the alarm time from [H:M] or [H:M:S] to seconds
seconds_hms = [3600, 60, 1] # Number of seconds in an Hour, Minute, and Second
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])

# Get the current time of day in seconds
now = datetime.datetime.now()
current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])

# Calculate the number of seconds until alarm goes off
time_diff_seconds = alarm_seconds - current_time_seconds

# If time difference is negative, set alarm for next day
if time_diff_seconds < 0:
    time_diff_seconds += 86400 # number of seconds in a day

# Display the amount of time until the alarm goes off
print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))

# Sleep until the alarm goes off
time.sleep(time_diff_seconds)

# Time for the alarm to go off
print("Wake Up!")

2. Представительный код помощника:

def assistant():
    command = input('command: ')
    if command == '1':
        print('is it one')
    elif command == '2':
        print('is it two')

while True:
    assistant()

Я планирую такой вывод

command: 1
is it one
command: 2
is it two
command: alarm
Set a time for the alarm (Ex. 06:30 or 18:30:00)
>> 13:00
Alarm set to go off in 1:30:00
command: 1
is it one
command: 2
is it two
Wake Up!
command: 1
is it one
command: 2
is it two

1 Ответ

0 голосов
/ 23 октября 2019

Я могу предоставить вам следующий пример:

from threading import Thread, Event
import time


def give_alarm(_e):  # create function for another parallel thread
    time.sleep(7)
    print("Alarm!!!")
    _e.clear()  # clear Event and notify main program thread


if __name__ == "__main__":
    e = Event()
    e.set()
    alarm = Thread(target=give_alarm, args=(e,), )  # start parallel thread
    alarm.start()

    while e.is_set():  # imagine that it is main program body/thread
        print("Hello")
        time.sleep(1)

    print("Continue!")

Лучший пример:

from threading import Thread, Event
import time


def give_alarm(_e):
    time.sleep(7)
    print("Alarm!!!")
    _e.clear()  # clear Event


def print_c(_e):
    for i in range(20):
        if not e.is_set():
            break
        print("CCC")
        time.sleep(1)


def print_b(_e):
    for i in range(20):
        if not e.is_set():
            break
        print("BBB")
        time.sleep(1)


if __name__ == "__main__":
    e = Event()
    while True:
        command = input("Give command: ")
        if command == "a":
            e.set()
            Thread(target=give_alarm, args=(e,), ).start()  # start parallel thread
        elif command == "c":
             e.set()
             Thread(target=print_c, args=(e,), ).start()
        elif command == "b":
             e.set()
             Thread(target=print_b, args=(e,), ).start()
        else:
            print("Wrong Input")

Надеюсь, этот пример был вам полезен, не стесняйтесь задавать вопросы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...