Search code examples
pythonpynput

How to make a loop on code in pynput without using ram and that is infinite


Im having a bit of trouble looping this code im new to python and coding and trying to make this an afk machine for a game i play

This is code that im trying to make that types something over and over infinitely, please help im trying to make an afk machine since my program i use ran out of trail days so im trying to make this im new to this so sorry for the stupid question but ive tried For loops and while loops and i cant get them to work

from pynput.keyboard import Key, Controller
import time


keyboard = Controller ()

time.sleep(0.1)
for char in "vcmine start":
    keyboard.press(char)
    keyboard.release(char)
    time.sleep(0.03)

keyboard = Controller()

keyboard.press(Key.enter)
keyboard.release(Key.enter)

Solution

  • I guess you could literally just do something like this.

    from pynput.keyboard import Key, Controller, Listener
    import time
    
    def on_press(key):
        print('{0} pressed'.format(
            key))
    
    def on_release(key):
        print('{0} release'.format(
            key))
        if key == Key.esc:
            # Stop listener
            return False
    
    # Collect events until released
    with Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    
    keyboard = Controller ()# You should only need to define this once
    while(True):# This will repeat the indented code below forever   
        time.sleep(0.1)
        for char in "vcmine start":
            keyboard.press(char)
            keyboard.release(char)
            time.sleep(0.03)
    
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
    # However the only way you can stop it is by closing the program
    

    This is pretty much just copied and pasted from https://pythonhosted.org/pynput/keyboard.html under the section Monitoring the Keyboard. First run the code, then place the cursor where you want the text to be typed, then by hitting the esc key on the keyboard the rest of the code will now run and will type what you want where you want it.

    Also note that if you run the code and then put the cursor in another text field while this is running it will start to type there instead.

    for and while loops can be confusing at first but definitely read up on them because they are used a lot in coding and are very useful. While Python is my favorite language it has a bit more variety with respect to how loops can be defined which might be kind of confusing at first.

    Use google ALOT to find tutorials and YouTube videos on the subject (there's tons of great info out there).