1

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)
Water Man
  • 302
  • 2
  • 9
  • Your Programm first execute the function call `book` and will only continue with the next line after that function has returned. Your requirement is asynchronous function call, take a look at this question https://stackoverflow.com/questions/1239035/asynchronous-method-call-in-python – Sparky05 Mar 07 '20 at 11:44

1 Answers1

1

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.

chuck
  • 1,420
  • 4
  • 19