Python simple counting script - python

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)

Related

I need the "if" to go once but not end the loop

I'm making a program to control the mouse with WASD but whenever I press the button the mouse just moves to the top of the screen when I need it to move slightly then be able to move again if I press the key again
I've tried to have the loop turn off then back on but it just ends the loop before it can switch back on.
import keyboard
from pynput.mouse import Controller
mouse = Controller()
repeat = True
while repeat:
if keyboard.is_pressed('w'):
mouse.move(0, -5)
if keyboard.is_pressed('s'):
mouse.move(0, 5)
I need it to move up slightly when I press w but stop when it isn't pressed so I can press it again.
You might want your keyboard not to be so sensitive, so you may need to sample the pressing time. sleep can help in this case. In the code below, the program will sleep for 0.2 seconds every time it enters while loop.
import keyboard
import time
repeat = True
while repeat:
time.sleep(0.2)
if keyboard.is_pressed('w'):
mouse.move(0, -5)
if keyboard.is_pressed('s'):
mouse.move(0, 5)
# do something
EDIT: I was misunderstanding what you want, just sleep is enough for this. The problem is because your computer does everything too fast, so a while loop might be completed in a microsecond or less. So it sees that you are pressing the key for too long (though you think you did fast) then it just repeats the loop until you release the key. That's why your mouse always moves to the top.
Sampling is the way to tell computer "if you've done, then sleep, don't do anything else".
Another way is to count how many times it loops (ie, scaling), but it looks like dump since the computer has to do worthless things.
import keyboard
from pynput.mouse import Controller
mouse = Controller()
repeat = True
w_count, s_count = 0, 0
while repeat:
if keyboard.is_pressed('w'):
w_count += 1
if w_count == 10: # i'm scaling it
mouse.move(0, -5)
w_count = 0
if keyboard.is_pressed('s'):
s_count += 1
if s_count == 10: # i'm scaling it
mouse.move(0, 5)
s_count = 0
There are also other ways: measure the pressing time, edge detection (detect key release)... You can search about "software debouncing" for more ideas and find one best fits your requirement.

Win32api: Press and Hold key

I'm looking for a way to press a key and hold it for a specific amount of time. I have tried:
# Method 1
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys
# Method 2
win32api.SendMessage
# Method 3
win32api.keybd_event
All of these methods, only seem to press a key once. I need to hold the key down.
I have looked at these resources: python simulate keydown (SO), win32api.keybd_event, press-and-hold-with-pywin32 (SO), simulate-a-hold-keydown-event-using-pywin32 (SO), Vitual keystroke (Github)
If you can use PyAutoGUI, this would do it:
import pyautogui
import time
def hold_key(key, hold_time):
start = time.time()
while time.time() - start < hold_time:
pyautogui.keyDown(key)
hold_key('a', 5)
It will keep the 'a' key pressed for 5 seconds.

Why don't these tkinter programs behave identically?

I have 2 codes I made. The 2nd one is based off of the first one. Unfortunately for some reason the 2nd one doesn't work even though the first one does.
First code:
import time
from Tkinter import *
root = Tk()
t=StringVar()
num=1
t.set(str(num)
thelabel = Label(root, textvariable=t).pack()
def printnum (x):
while x<= 100:
t.set(str(x))
x += 1
root.update()
time.sleep(30)
printnum(num)
root.mainloop()
This code works like a charm. Here is the other one.
Second code:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import Adafruit_DHT as dht
import time
from Tkinter import *
root = Tk()
k=StringVar()
num = 1
k.set(str(num))
thelabel = Label(root, textvariable=k).pack
def printnum(x):
while x <= 10000000000000:
h,t = dht.read_retry(dht.DHT22, 4)
newtext = "Temp%s*C Humidity=%s" %(t,h)
k.set(newtext)
x += 1
root.update
time.sleep(30)
printnum(num)
root.mainloop()
The code runs but it doesn't do anything, no window pops up like the other code does. Please help I cannot figure out how to fix this. Or why the first one works and the second one doesn't.
You're overwriting the previous value of t with the temperature from read_retry on this line:
h,t = dht.read_retry(dht.DHT22, 4)
Then, when you try to call set, t is now a float, so doesn't have a set method. Use a different variable name instead of t for one of them.
root.update doesn't do anything. You need to add ():
root.update()
That being said, your algorithm is the wrong way to run periodic tasks in tkinter. See https://stackoverflow.com/a/37681471/7432

Inputting double digit numbers from keyboard on Tkinter, Python

So I'm using the following to enable single digit numbers to move the numbered tiles on my game board. However, I can't use the same method to input double digit numbers. Do you have any idea, how I could make Tkinter wait for me to input several digits as one number?
def key(event):
if event.char.isdigit():
for j, row in enumerate(board):
for i, char in enumerate(row):
if char.get() == event.char:
play(i,j)
return
root.bind('<Key>', key)
As I mention in previous question - you can put keys on list, wait a moment and check if there are two or more chars.
import tkinter as tk
''' catch two (or more) keys pressed in short time and tread it as one text '''
''' http://pastebin.com/WHQKcJkW '''
# --- functions ---
# keys buffer
keybuf = []
def test_after():
# check if buffer is not empty
if keybuf:
# get all keys in buffer as one text
text = ''.join(keybuf)
# clear buffer
keybuf.clear()
# run some function here
print('after:', text)
def get_key(event):
# save key in buffer
keybuf.append(event.char)
# check buffer after 500ms (0.5s)
root.after(500, test_after)
# --- main ---
root = tk.Tk()
root.bind('<Key>', get_key)
root.mainloop()

Python: get key event and output something else

Using Python and C (or just Python) how can I receive every pressed key from the keyboard while my program is running and output to the screen other key? For example, if user inputs 'F' it outputs 'ph'.
Thank you
You can use msvcrt.getch() to get the key, and then map that to a value in a dictionary:
from msvcrt import getch
chars = {b'f': 'ph'} # You could easily extend this dictionary.
while True:
z = getch()
if z in chars:
print(chars[z])

Categories