How to make the key.click() repeatedly work? - python

I'm trying to make an autoclicker, but it's currently only clicking once when I press a random key that isn't esc.
import keyboard
import time
import pyautogui as key
time.sleep(4)
Count=0
while True:
key.click()
print('Click')
Count=Count+1
if keyboard.read_key()=='esc':
print("Quit!", Count)
break

The below code will keep clicking till a key (esc) is pressed:
from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep
sleep(4)
count = 0
while not isp('esc'):
click()
print('clicky')
count += 1
print('\nDone! Times clicked:\t', count)
If you want to do it only when a key is pressed:
from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep
sleep(4)
count = 0
while not isp('esc'):
if isp('some key'):
click()
print('clicky')
count += 1
print('\nDone! Times clicked:\t', count)
Also don't EVER use while True with pyautogui, it's especially dangerous. Unless you know to trigger the failsafe, you basically can't stop if the break statement goes wrong. Take it from someone who has made that mistake.

Related

stuck on adding a timer to my keyboard press program

Im making a keyboard program that repeatedly presses a key every 0.1 seconds and uses esc as the hotkey to stop/start the program.
import keyboard
import time
keyboard.wait('esc')
name = ("python")
while name == "python":
keyboard.press_and_release('5')
time.sleep(0.1)
#this is where i want to add the timer
name = ("notpython")
I want to add the timer there so that after a few seconds the name variable changes from python to notpython and making the while loop false.
I've tried the time sleep function but it keeps printing 5 and doesnt stop.
maybe you can try something like this:
import keyboard
import time
keyboard.wait('esc')
name = ("python")
timer = time.time()
while name == "python":
keyboard.press_and_release('5')
time.sleep(0.1)
timer2 = time.time()
if timer2 - timer >= 5: name = "notpython"

problems with failsafe and threading

I am trying to make a python autoclicker as seen below:
import queue
from pynput import mouse
from pynput.mouse import Controller, Button
from sys import exit
from threading import Thread
from time import sleep
from keyboard import is_pressed
mouse = Controller()
failSafeKey = 'q'
delay = 1
def clicking():
while TRUE:
mouse.click(Button.left)
sleep(delay)
def failSafe():
while TRUE:
if is_pressed(failSafeKey):
exit()
print("exiting")
sleep(0.1)
delay = float(input("Enter delay: "))
failSafeKey = input("Enter failsafe key (ex. ctrl+s or q): ")
Thread(clicking())
Thread(failSafe())
However, whenever I press the failsafe key, nothing happens. I have tried removing the threads, but nothing changed. Can anyone give pointers on what might be happening?

Stopping a python program when an arbitrary key was pressed while the program is running

I recently got to know about the python module signal. With that, we can capture a SIGINT and do what we want after capturing it. I used it as below. In that case I am just using SIGINT to print that program is going to be stopped and stop the program.
import signal
import os
import time
def signalHandler(signalnumb, frame):
print("Signal Number:", signalnumb, " Frame: ", frame)
print('Exiting the program...')
os._exit(0)
signal.signal(signal.SIGINT, signalHandler)
c=0
# Loop infinite times using the while(1) which is always true
while 1:
print(c)
#sleep for 1 seconds using the sleep() function in time
time.sleep(1)
c=c+1
Now I want to give any signal from keyboard(for example pressing 'q') and as soon as signal was recieved, the python program should be stopped. Has anyone got some experience on how to do that? Any other method rather than using signal module (for example using multithreading) is accepted.
Edit1-
Later I tried to use pynput module as suggested in one of a similar kind of question. For sure I have done a mistake. It doesn't work as I expected. It means with a key press, I couldn't stop the for loop from running.
from pynput import keyboard
import time
def on_press(key):
for i in range(100):
print(i)
time.sleep(1)
if key == keyboard.Key.esc:
return False # stop listener
try:
k = key.char # single-char keys
except:
k = key.name # other keys
if k in ['1', '2', 'left', 'right']: # keys of interest
# self.keys.append(k) # store it in global-like variable
print('Key pressed: ' + k)
return False # stop listener; remove this if want more keys
listener = keyboard.Listener(on_press=on_press)
listener.start() # start to listen on a separate thread
listener.join() # remove if main thread is polling self.keyspython
Can someone point out how to do it using pynput in correct way?
This was my original implementation:
a = input('Press a key to exit')
if a:
exit(0)
However, it seems that you need a piece of code that will allow for any key to be clicked and immediately exit out of the program, without hitting enter afterwards. This may be a better way to do that:
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()
Hope this helps!
After carefully understanding about the threads and pynput module, I managed to stop a for loop (or any program which runs as a separate thread) using a key press callback.
from pynput import keyboard
import os
import threading
import time
loop_running = False
def on_press(key):
print(dir(key))
global loop_running
#if key == keyboard.Key.delete and not loop_running:
if ('char' in dir(key)) and (key.char == 's') and (not loop_running):
t=threading.Thread(target=start_loop)
t.start()
#elif key==keyboard.Key.tab: #if this is used, the attributes related to 'key' will be changed. you can see them since I have used a print(dir(key))
elif key.char == 'q':
loop_running=False
def start_loop():
global loop_running
loop_running = True
for i in range(100):
if not loop_running:
os._exit(0)
print(i)
time.sleep(1)
with keyboard.Listener(on_press=on_press) as listner:
listner.join()

how to terminate pynput keyboard listener with a timer or a pressed key?

I know how to terminate pynput keyboard listener with a timer or with a specific key to be pressed (they are both discussed here in this forum).
I cannot find a way to mix the 2 so that the listener is terminated after a preset amount of time or before that time if a specific key (Key.end for example is pressed)
I tried many combinations but none of them work so far.
added after #martineau comments:
an apparently natural way to do it could be:
from pynput import keyboard as kb
from time import time
exit_script=False
def action_press(key):
global exit_script
if key == kb.Key.end:
print ('end pressed')
exit_script= True
return False
timeOn=10
t0=time()
with kb.Listener(on_press=action_press,suppress=True) as l:
while exit_script== False and time()-t0<timeOn:
pass
l.join()
print('listener terminated')
But it fails to terminate with the timer criteria.
Does somebody know how correct this or if there is an alternative approach??
Thks
Ok I just found one answer using pynput controller. It does the trick.
from pynput import keyboard as kb
from time import time
mykb=kb.Controller()
exit_script=False
def action_press(key):
global exit_script
if key == kb.Key.end:
print ('end pressed')
exit_script= True
return False
timeOn=10
t0=time()
with kb.Listener(on_press=action_press,suppress=True) as l:
while exit_script== False:
if time()-t0>timeOn:
mykb.press(kb.Key.end)
mykb.release(kb.Key.end)
l.join()
print('listener termianted')

Press a key in a batch script with Python

I have a script in python that execute a batch program that need press two or three times the "d" key and after the "q" key.
I tried this but without solution:
import os
import keyboard
import time
from pynput.keyboard import Key, Controller
os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)
keyboard = Controller()
keyd = "d"
keyq = "q"
keyboard.press(keyd)
keyboard.release(keyd)
time.sleep(3)
keyboard.press(keyq)
keyboard.release(keyq)
Only open the console but the script don't press the keys, but if you press with the keyboard the program works fine.
You could try to use the subprocess module.
Example:
subprocess-test.py
import subprocess
p = subprocess.Popen(["python", "input-app.py"], stdin=subprocess.PIPE)
p.stdin.write("Hello\n".encode(encoding='UTF-8'))
p.stdin.write("World\n".encode(encoding='UTF-8'))
input-app.py
input1 = input("Input 1: ")
input2 = input("Input 2: ")
print(input1, input2)
See more information here:
https://docs.python.org/3/library/subprocess.html
https://stackoverflow.com/a/3684694/42659
Sorry, I won't be able to help more as I only have a short lunch break. I hope this already does help though or points you in the right direction!
You can use: pyautogui for pressing code as simply as:
import pyautogui
pyautogui.press('d')
Your case can be handled as follows:
import os
import pyautogui
import time
os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)
keyd = "d"
keyq = "q"
pyautogui.press(keyd)
time.sleep(3)
pyautogui.press(keyq)
If pressing keys don't work, you may try to enter exact strings as well:
import os
import pyautogui
import time
os.system('"C:/Users/xxx/Documents/Software/xxx.exe 192.168.0.15"')
time.sleep(5)
keyd = "d"
keyq = "q"
pyautogui.write(keyd)
time.sleep(3)
pyautogui.write(keyq)

Categories

Resources