How to pop up an alert in Python and at the same time keep the process running?

Question:

I have a sample script below. The alert message will pop up but the user will have to acknowledge before the script could continue to run. So how do I pop up an alert in Python and at the same time keep the process running?

import random
import time
x = 0
while x <= 20:
    a = random.randint(1, 100)
    print (a)
    if a <= 10:
        ctypes.windll.user32.MessageBoxW(0, "The number generated is less than 10", "ALERT", 1)
    x += 1
    time.sleep(.5)
Asked By: Juls

||

Answers:

Use threading.Thread.

This launches the alert in a separate thread, so that it does not block the main thread.

import random
import time
import threading

def alert():
    ctypes.windll.user32.MessageBoxW(0, "The number generated is less than 10", "ALERT", 1)

for _ in range(20):
    a = random.randint(1, 100)
    print (a)
    if a <= 10:
        thread = threading.Thread(target=alert)
        thread.start()
    time.sleep(.5)
Answered By: Jérôme

Or on *nix using Notify from the gi.repository

import random
import time
import threading
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify

def alert():
    Notify.init("Random generator")
    Notify.Notification.new("The number generated is less than 10").show()

for _ in range(20):
    a = random.randint(1, 100)
    print (a)
    if a <= 10:
        thread = threading.Thread(target=alert)
        thread.start()
    time.sleep(.5)
Notify.uninit()
Answered By: Psionman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.