Python Forum
Hotkey to restart code? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Hotkey to restart code? (/thread-26960.html)



Hotkey to restart code? - DannyB - May-20-2020

Im looking to add f2 as a hotkey to go to a certain point in the code. This would allow a user to reconfigure the settings.
This is the full code:

from pynput.keyboard import Key, Controller
from pynput import keyboard
import pynput
import time
import os

COMBINATIONS = [
    {keyboard.Key.f8},
]

current = set()
keyboard = pynput.keyboard.Controller()

print('Spammer 2.1\n')

#configuration
while True:
    response = input('Enter Delay (Milliseconds): ')
    try:
        number = int(response)
        break 
    except ValueError:
        print('Invalid Input. Only Use Whole Numbers.\n')
        
delay = (number/100)

print('Delay Set to:', delay,'Seconds\n')
text = (input('Enter Message to be Sent: '))
print('Message Set to:', text,'\n')
print('Setup Complete.')
print('Press F8 to Start Spamming.')
#end configuration


def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            execute()
            
def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

def look_for_stop(key):
    if key == Key.esc:
        return False
            
def execute():
    x = 0
    countdown = ["3","2","1"]
    print('\nSpamming in:(Press ESC to Stop)')
    for i in countdown:
        time.sleep(1)
        print(i)
    time.sleep(1)
    print('\nSpamming...')
    start = time.time()
    with pynput.keyboard.Listener(on_press=look_for_stop) as listener:
        while True:
            x = x+1
            time.sleep(delay)
            keyboard.type(text)
            keyboard.press(Key.enter)
            keyboard.release(Key.enter)
            print('Messages Sent:',x)
            if not listener.running:
                print('\nSpam Stopped')
                stop = time.time()
                print('Time Elapsed:', stop-start,'Seconds')
                print('\nPress F8 to Continue Spamming.\nPress F2 to Reconfigure setup.')
                break

with pynput.keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()



RE: Hotkey to restart code? - michael1789 - May-20-2020

The most straightforward way would be add a keydown event check, like you do with "enter", and when it is hit run a function that is an options menu.