Water Man
Water Man

Reputation: 323

Python can you ignore time.sleep outside of function but not inside?

I want to execute a function that waits a certain of time between printing text, but when you call the function it doesnt wait there. Here's my code

import keyboard, time

def book1():
    print("This is a book")
    time.sleep(2)
    print("These are the contents of the book")

def book2():
    print("This is another book")
    time.sleep(2)
    print("These are the contents of the book")  

books = {
    "a": book1,
    "b": book2
}

def scan_key(key):
    if key.name in books.keys():
        if key.event_type == keyboard.KEY_DOWN:
            book = books[key.name]
            print("Reading book")
            book()
            #This should be printed right after "Reading book" without any wait
            print("Hello")

hook = keyboard.hook(scan_key)

Upvotes: 1

Views: 241

Answers (1)

chuck
chuck

Reputation: 1447

You should use threads to allow the program to execute several instructions concurrently:

import threading

def scan_key(key):
    if key.name in books.keys():
        if key.event_type == keyboard.KEY_DOWN:
            book = threading.Thread(target=books[key.name])
            print("Reading book")
            book.start()
            #This should be printed right after "Reading book" without any wait
            print("Hello")
            book.join()

This will achieve the result.

Upvotes: 1

Related Questions