多线程(多处理),但让一个线程在另一个线程中的同时在后台运行?

时间:2021-07-24 13:26:59

标签: python multithreading function python-multiprocessing

这是我新造的生命机器,有一个特定的功能,通知! 在这里你可以看到我的代码!

import sqlite3
import pickle
from datetime import datetime
import time
from win10toast import ToastNotifier
from multiprocessing import Process

notification = False
notify = ""
message = ""


def setup():
    connection = sqlite3.connect('info.s3db')  # connecting to our main database :)
    cursor = connection.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS Machine ('
                   'id INTEGER PRIMARY KEY AUTOINCREMENT,'
                   'tasks TEXT,'
                   'extra BOOLEAN DEFAULT FALSE,'
                   'completion BOOLEAN DEFAULT FALSE);')
    connection.commit()


def UI1():  # Interface 1
    global notification, notify, message
    setup()  # connects to database, and setup everything.
    if notification:
        notifier = Process(target=TASKNOTIFY())
        notifier.start()

    option = str(input("Welcome to lifeAI, always innovating and improving your life!\n"
                       "Remember to update your tasks everyday!\n"
                       "0. Update task status\n"  # English version
                       "1. Check tasks\n"
                       "2. Balance\n"
                       "3. Monthly Spending(IRL)\n"
                       "4. Exit\n"
                       "5. Exchange\n"
                       "6. Add tasks\n"
                       "7. Delete tasks\n"
                       "8. Finished tasks\n"
                       "9. Reset balance\n"
                       "10. Add notifications(Only in this current day)\n"
                       "11. Delete all tasks\n"))
    if option == "0":
        TASKUPDATE()

    elif option == "1":
        TASKCHECK()

    elif option == "2":
        BALANCECHECK()

    elif option == "3":
        IRLCalculator()

    elif option == "4":
        EXIT()

    elif option == "5":
        EXCHANGE()

    elif option == "6":
        ADDTASK()

    elif option == "7":
        TASKDEL()

    elif option == "8":
        TASKFINISH()

    elif option == "9":
        option = str(input("Are you sure you want to do this(Y/N)?\n"))
        if option == "Y":
            credit = 0
            with open('credit.dat', 'wb') as file:
                pickle.dump(credit, file)

    elif option == "10":
        if not notification:
            notify = input("Type in your notification time(Today) in the format of HH:MM:SS;\n"
                           "Enter:")
            # Format the current time
            try:
                time.strptime(notify, '%H:%M:%S')
                message = str(input("Please type the reminder you want to see(only 1 reminder can be set at a "
                                    "time): \n"))
                notification = True
            except ValueError:
                print('LifeAI reminds you that your input has some problems, it might not be in the right format.')
        else:
            reset = str(input("There is a current notification already! Do you want to reset(Y/N)?"))

            if reset == "Y":
                notification = False

            else:
                pass
    elif option == "11":
        ALLTASKDELETE()

    else:
        print("LifeAI couldn't quite understand your commands.")


def TASKNOTIFY():
    global notification, message, notify
    while True:
        toaster = ToastNotifier()
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        if notification:
            if current_time == notify:
                # throw the notification
                toaster.show_toast("LifeUI, FDS", message, icon_path=None, duration=15, threaded=True)
                notification = False


def ALLTASKDELETE():
    choice = str(input("Are you sure you want to do this(Y/N):\n"))
    if choice == "Y":
        connection = sqlite3.connect('info.s3db')
        cursor = connection.cursor()
        # noinspection SqlWithoutWhere
        cursor.execute("""DELETE FROM Machine;""")
        connection.commit()


def TASKUPDATE():
    connection = sqlite3.connect('info.s3db')
    cursor = connection.cursor()
    cursor.execute("UPDATE Machine SET completion = FALSE")
    print("Tasks successfully updated!")
    connection.commit()


def EXIT():
    print("Thank you for choosing LifeAI. Have a good day.")  # Leaving the AI
    exit()


def BALANCECHECK():
    try:
        with open('credit.dat', 'rb') as file:
            credit = pickle.load(file)
    except:
        credit = 0
    print(f"Balance: {credit}")


def IRLCalculator():
    amount = int(input("Money: "))
    days = int(input("Days of this month: "))
    each_day = amount / (days - 8)
    bus_fare = 5
    food = 15
    train_fare = 7
    daily_fare = bus_fare + food + train_fare
    monthly_fare = daily_fare * (days - 8)
    daily_save = each_day - daily_fare
    monthly_save = daily_save * (days - 8)
    print(f"Amount of money used everyday(Basic): {daily_fare}\n"
          f"Amount of money used in a month(Basic): {monthly_fare}\n"
          f"Amount of money saved everyday(Basic): {daily_save}\n"
          f"Amount of money saved in a month(Basic): {monthly_save}\n")
    extra_save = float(input("How much do you want to save this month(Extra)(Put it in decimals): "))
    required = each_day * extra_save
    if food - required <= 5:
        print("Nothing able to be saved.")
    else:
        print(f"Amount of food money now(Changed): {food - required}"
              f"Amount of money saved everyday(Basic): {daily_save + required}\n"
              f"Amount of money saved in a month(Basic): {monthly_save + required * (days - 8)}\n")


def ADDTASK():
    while True:
        connection = sqlite3.connect('info.s3db')
        cursor = connection.cursor()
        status = str(input(f"Extra or Compulsory?(E/C)(Type End to exit)"))
        if status == "C":
            new_task = str(input(f"Enter a new task, to leave enter 'End': "))
            if new_task == "End":
                break
            cursor.execute("""INSERT INTO Machine (extra, completion, tasks) VALUES (False, False, ?)""", (new_task,))
            connection.commit()
        elif status == "E":
            new_task = str(input(f"Enter a new task, to leave enter 'End': "))
            if new_task == "End":
                break
            cursor.execute("""INSERT INTO Machine (extra, completion, tasks) VALUES (True, False, ?)""", (new_task,))
            connection.commit()
        elif status == "End":
            break
        else:
            print("LifeAI couldn't quite understand what you said. Please repeat it again!")


def TASKCHECK():
    connection = sqlite3.connect('info.s3db')
    cursor = connection.cursor()
    cursor.execute("""SELECT tasks FROM Machine WHERE completion = False AND extra = False""")
    tasks = cursor.fetchall()
    cursor.execute("""SELECT tasks FROM Machine WHERE completion = False AND extra = True""")
    extra = cursor.fetchall()
    if not tasks:
        print("No tasks today!\n")
    else:
        thing = ' '.join(map(str, tasks))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("(", "")
        thing = thing.replace(")", "")
        tasks = thing.replace("'", "")
        print(f"Your tasks(compulsory): {tasks}\n")
    if not extra:
        print("No extra tasks today!\n")
    else:
        thing = ' '.join(map(str, extra))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("(", "")
        thing = thing.replace(")", "")
        extra = thing.replace("'", "")
        print(f"Your tasks(extra): {extra}\n")


def TASKDEL():
    connection = sqlite3.connect('info.s3db')
    cursor = connection.cursor()
    while True:
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = FALSE AND extra = FALSE""")
        tasks = cursor.fetchall()
        thing = ' '.join(map(str, tasks))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        tasks = thing.replace(")", "")
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = TRUE and extra = TRUE""")
        tasks1 = cursor.fetchall()
        thing = ' '.join(map(str, tasks1))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        tasks1 = thing.replace(")", "")
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = FALSE and extra = TRUE""")
        extra = cursor.fetchall()
        thing = ' '.join(map(str, extra))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        extra = thing.replace(")", "")
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = TRUE and extra = TRUE""")
        extra1 = cursor.fetchall()
        thing = ' '.join(map(str, extra1))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        extra1 = thing.replace(")", "")
        option = str(input("Extra or Compulsory?(E/C)(Type End to exit)"))
        if option == "C" and tasks != "" or tasks1 != "":
            delete_task = str(input(f"Type the entire task to delete it(End to leave):\n "
                                    f"Uncompleted(compulsory): {tasks}\n"
                                    f"Completed(compulsory): {tasks1}\n"))
            if delete_task == "End":
                break
            try:
                connection = sqlite3.connect('info.s3db')
                cursor = connection.cursor()
                cursor.execute("""DELETE FROM Machine WHERE tasks LIKE ?""", (delete_task,))
                connection.commit()
            except sqlite3.Error:
                print("No tasks to delete.")
        elif option == "E" and extra != "" or extra1 != "":
            delete_task = str(input(f"Type the entire task to delete it(End to leave):\n "
                                    f"Uncompleted(extra): {extra}\n"
                                    f"Completed(extra): {extra1}\n"))
            if delete_task == "End":
                break
            try:
                connection = sqlite3.connect('info.s3db')
                cursor = connection.cursor()
                cursor.execute("""DELETE FROM Machine WHERE tasks LIKE ?""", (delete_task,))
                connection.commit()
            except sqlite3.Error:
                print("No tasks to delete.")
        elif option == "End":
            break
        else:
            print("Nothing to delete!")
            break


def TASKFINISH():
    connection = sqlite3.connect('info.s3db')
    cursor = connection.cursor()
    while True:
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = FALSE AND extra = FALSE""")
        tasks = cursor.fetchall()
        thing = ' '.join(map(str, tasks))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        tasks = thing.replace(")", "")
        cursor.execute("""SELECT tasks FROM Machine WHERE completion = FALSE AND extra = TRUE""")
        extra = cursor.fetchall()
        thing = ' '.join(map(str, extra))  # Ugly code to replace the unwanted stuff
        thing = thing.replace("'", "")
        thing = thing.replace("(", "")
        extra = thing.replace(")", "")
        status = str(input("Extra or Compulsory?(E/C)(Type End to exit)"))
        if status == "C":
            option = str(input(f"Tasks today: {tasks}\n"
                               f"Every completed (compulsory) task will give you 10 points;(Type the name)(Type End to "
                               f"leave):\n"))
            if option == "End":
                break
            cursor.execute("""UPDATE Machine SET completion = TRUE WHERE tasks = ? AND extra = FALSE""", (option,))
            try:
                with open('credit.dat', 'rb') as file:
                    credit = pickle.load(file)
            except:
                credit = 0
            credit += 10
            with open('credit.dat', 'wb') as file:
                pickle.dump(credit, file)
        elif status == "E":
            option = str(input(f"Tasks today: {extra}\n"
                               f"Every completed (extra) task will give you 5 points;(Type the name)(Type End to "
                               f"leave):\n"))
            if option == "End":
                break
            cursor.execute("""UPDATE Machine SET completion = TRUE WHERE tasks = ? and extra = TRUE""", (option,))
            try:
                with open('credit.dat', 'rb') as file:
                    credit = pickle.load(file)
            except:
                credit = 0
            credit += 5
            with open('credit.dat', 'wb') as file:
                pickle.dump(credit, file)
        elif status == "End":
            break
        else:
            print("LifeAI couldn't quite understand what you typed.")


def EXCHANGE():
    while True:
        try:
            with open('credit.dat', 'rb') as file:
                credit = pickle.load(file)
        except:
            credit = 0
        option = str(input(f"You have {credit} credits! What would you like to buy?(Type End to exit)\n"
                           f"1. 10 Minutes of playing time(5)\n"
                           f"2. 30 Minutes of playing time(15) DISCOUNT\n"
                           f"3. 60 Minutes of playing time(40) DISCOUNT\n"
                           f"4. Extra 5 Drink Money(15)\n"
                           f"5. Extra 10 Drink Money (25) DISCOUNT\n"
                           f"6. Youtube Music(1000) 1 MONTH\n"
                           f"7. Basketball Gear(2000)\n"
                           f"8. Eat dessert (500)\n"))
        if option == "End":
            break
        elif option == "1":
            if credit >= 5:
                print("Successfully bought! You've earned yourself 10 minutes.\n")
                credit -= 5
            else:
                print("Not enough points.\n")
        elif option == "2":
            if credit >= 15:
                print("Successfully bought! You've earned yourself 30 minutes.\n")
                credit -= 15
            else:
                print("Not enough points. \n")
        elif option == "3":
            if credit >= 40:
                print("Successfully bought! You've earned yourself 60 minutes.\n")
                credit -= 40
            else:
                print("Not enough points. \n")
        elif option == "4":
            if credit >= 15:
                print("Successfully bought! You've earned yourself extra 5 dollars for drinks.")
                credit -= 15
            else:
                print("Not enough points. \n")
        elif option == "5":
            if credit >= 25:
                print("Successfully bought! You've earned yourself extra 10 dollars for drinks.")
                credit -= 25
            else:
                print("Not enough points. \n")
        elif option == "6":
            if credit >= 1000:
                print("Successfully bought! You've earned yourself a month of music.")
                credit -= 1000
            else:
                print("Not enough points. \n")
        elif option == "7":
            if credit >= 2000:
                print("Successfully bought! You've earned yourself some basketball gear.")
                credit -= 2000
            else:
                print("Not enough points. \n")
        elif option == "8":
            if credit >= 500:
                print("Successfully bought! You've earned yourself some dessert.")
                credit -= 500
            else:
                print("Not enough points. \n")

        with open('credit.dat', 'wb') as file:
            pickle.dump(credit, file)


# starting the magic

MainUI = Process(target=UI1())
MainUI.start()

跳到选项 10 的部分。您设置通知并设置时间。 现在在 UI1 while 循环的顶部,它检查条件是否通知为真,并且时间合适。但问题是即使时间合适,通知也不会显示。现在这是使用多处理,但它并没有真正多处理任何东西。发生的情况是,当notifier进程运行时,mainui进程会等待它结束,导致程序为空,直到通知出现,然后才恢复正常。谁能解释一下为什么?

0 个答案:

没有答案