Open random video file on a keypress

Viewed 140

I am trying to write a program in Python that will open a random video file on a keypress(for me F8). I am very new to coding and currently stuck. I got it to the point where I am not getting any errors but now the program is not sticking around. Not sure what to do next. My code:

import os
import keyboard
import string
import random
from openfile import openfile


path = r"C:\Users\Rudy\Videos\GIFS"

letter = string.ascii_letters 
digit = string.digits     
def keyboardPress():
    mp3Select = random.choice(os.listdir(path)) 
    keypress = str(path + "\\" + mp3Select) 
    while True:
            if keyboard.is_pressed('F8'): 
                openfile(keypress)
            break

def main():
    while True:
        try:
            keyboardPress()
        except:
            pass

main()
1 Answers

To open a random video on key press, you can use the event hooks in the keyboard module, one such event hook is keyboard.on_press(callback) which invokes a callback for every keydown event.

To prevent the program from terminating, you can use the method keyboard.wait(hotkey=None) which blocks the program execution until the given hotkey is pressed.

Use:

def keyPress(event):
    if event.name == 'f8': # filter the `f8` key press event
        fileName = random.choice(os.listdir(path))
        filePath = os.path.join(path, fileName)
        openfile(filePath) # open the video file

def main():
    keyboard.on_press(keyPress) # hook up the event handler
    keyboard.wait('esc') # blocks the program execution until `escape` key is pressed.

main()

Edit (see comments):

Use this while calling main():

try:
    main()
except Exception as ex:
    print(ex)
Related