简体   繁体   中英

Python simple counting script

Im trying to make a script that automatically counts and uses SendKeys to print out a range of numbers ,say 1 - 100. I can make the list but I dont know how to convert the numbers so SendKeys can type them out because so far I can only make it type keys.

from pynput.keyboard import Key, Controller
import time
keyboard = Controller()

count = 0

for i in range (1, 100) :
count = count + 1

time.sleep(5)
keyboard.press(i)
keyboard.release(i)

You're basically there. You don't need count , and you need to send the string of the key you want to press, and presumably a new line. As a shortcut you could use the Controller.type method.

from pynput.keyboard import Controller, Key
import time

keyboard = Controller()

def send_range(start, end, wait_time):
    for i in range(start, end+1):
        keyboard.type(str(i))
        keyboard.press(Key.enter)
        time.sleep(wait_time)

send_range(1, 100, 5)
import time
from pynput.keyboard import Controller
keyboard = Controller()

for i in range(0,101):
    keyboard.type(str(i)+'\n')
    time.sleep(5)

Remove '\\n' if u want to print in same line

If you want the easiest solution, you can use keyboard.type() to send the characters in the integer one after another.

from pynput.keyboard import Controller, Key
import time

keyboard = Controller()

for i in range(1,100):
    time.sleep(5)
    keyboard.type(i)

If you still want to use keyboard.press() and keyboard.release() , for example if you want to sleep between each key press rather than between each integer in the list, then you can convert your integer into a string and then iterate through the string, like so

from pynput.keyboard import Controller, Key
import time

keyboard = Controller()

for i in range(1,100):
    time.sleep(5)
    for j in str(i):
        keyboard.press(j)
        keyboard.release(j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM