How to press down a key? - python

Been using the pyautogui module to do most of my things, but I have come across one problem:
I cannot hold down a key for a certain length of time.
Does anyone know any modules that can do this, or have a solution without downloading any modules?
For example (perfect for me):
I go into word, and run my code. Word should just be receiving (w pressed down), with the w's slowly increasing - (after a while holding adds like 5 a half sec).

You can use the following example:
>>> pyautogui.keyDown('shift') # hold down the shift key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.keyUp('shift') # release the shift key
In your case you'd use the keyDown function and a timer or equivelent to trigger keyUp.
You can find more information in regards to using timers here or better yet use Timer from the threading library - especially if you want to the processing to continue.
Example of using threading.Timer below.
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
In the keyDown documentation one can note the following:
NOTE: For some reason, this does not seem to cause key repeats like
would happen if a keyboard key was held down on a text field.
An alternative to using the keyDown function is to repeat the press function; in cases where keyDown is not satisfying the behaviour required by the developer and/or user.
def hold_key(key, hold_time):
import time, pyautogui
start_time = time.time()
while time.time() - start_time < hold_time:
pyautogui.press(key)
or
import pyautogui
while True:
pyautogui.press('w')
The above code is not tested.

Related

Trying to accept the keyboard input 'R' alone or along side any other amount of keyboard inputs using either keyboard or pygame modules

import keyboard
import pygame
import mouse
import time
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
#SA_R_X V_1.0
#------------------------------------------
while True:
try:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
except:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
the problem is the code cannot detect if 'r' is pressed when i am holding 'w' and/or 'space'... (well any key really)
I tried to use a try and except to handle a combination of any key + 'r'. But it did not work. All I need is for the code to be able to detect an 'r' input even if I am pressing/ holding another key at the same time. Then after this the code waits 0.2 seconds before holding down the 'x' key for 0.6 seconds and releasing. Any help is appreciated and it would be very helpful if you included a short explanation on where I went wrong and how you fixed it.
The documentation for this module can be found here. This is where all relevant information can be found.
The best way to do this, from my understanding, is to use an alternative function. If you want the program to continue to run, even though the key has not been pressed, then I suggest using the keyboard.on_press_key() function. This would mean that the rest of your program could still run, and your press_X() function could be run as a callback. Here is an example of how this code could be implemented.
import keyboard
import pygame
import mouse
import time
class App:
running = True
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
App.running = False
#SA_R_X V_1.0
#------------------------------------------
keyboard.on_press_key('r', lambda x: press_X()) ## Adds an event listener for the r key
## This will stop execution if there is no code after this point
If you want it to stop the program and wait for the r key to be pressed, then you could use keyboard.wait(). This will basically pause your program until the key is pressed, after which your function would be run. For example, to replace the keyboard.on_press_key('r', lambda x: press_X()):
keyboard.wait('r')
press_X()
From my understanding, keyboard.add_hotkey() does not work in your situation because it is looking for an exact combination of keys being pressed, such as Ctrl+C, and will only go if only the keys in the hotkey are pressed.
I hope this helps, good luck!

my program wont receive inputs while I'm on other tabs [duplicate]

I wrote a simple python script that gives control over the cursor to a joystick. My way to find out how this works is documented here. Now that works flawlessly but, as soon as I start the script to use the joystick, the mouse is useless, because my python routine sets the value back to its original, whenever a new joystick event comes in.
Thus I want my joystick events to be ignored as long as a key of the keyboard is pressed. I came across the pygame.key.get_pressed() method but this seems to work only, if the pygame window is in focus. I want this script running in background. Should I start using non-pygame events to listen to the keyboard or are there ways to keep track of the keyboard events analogue to the joystick events, which are recognized in background, via pygame?
I expect pygame sets up its own "sandbox" so that it's hard to detect input from outside its window. Your previous question indicates that you are also using the win32api module. We can use that to detect global key presses.
The correct way to detect key presses at the global scope is to set up a keyboard hook using SetWindowsHookEx. Unfortunately, win32api does not expose that method, so we'll have to use a less efficient method.
The GetKeyState method can be used to determine whether a key is down or up. You can continuously check the state of a key to see if the user has pressed or released it lately.
import win32api
import time
def keyWasUnPressed():
print "enabling joystick..."
#enable joystick here
def keyWasPressed():
print "disabling joystick..."
#disable joystick here
def isKeyPressed(key):
#"if the high-order bit is 1, the key is down; otherwise, it is up."
return (win32api.GetKeyState(key) & (1 << 7)) != 0
key = ord('A')
wasKeyPressedTheLastTimeWeChecked = False
while True:
keyIsPressed = isKeyPressed(key)
if keyIsPressed and not wasKeyPressedTheLastTimeWeChecked:
keyWasPressed()
if not keyIsPressed and wasKeyPressedTheLastTimeWeChecked:
keyWasUnPressed()
wasKeyPressedTheLastTimeWeChecked = keyIsPressed
time.sleep(0.01)
Warning: as with any "while True sleep and then check" loop, this method may use more CPU cycles than the equivalent "set a callback and wait" method. You can extend the length of the sleep period to ameliorate this, but the key detection will take longer. For example, if you sleep for a full second, it may take up to one second between when you press a key and when the joystick is disabled.
when your window gains or looses focus you get an ACTIVEEVENT. It's gain and state attributes tell you which state you've gained or lost. The easisest solution would probably be to catch this events in your main event loop and use them to keep track weather you have focus or not. Then you can just ignore joystick events if you don't have the focus.

pyautogui keydown and keyup arent working properly python

so I'm using pyautogui to type, and I'm trying to hold a key down for more than a second but I've ran into this problem where the key only types a single letter
import pyautogui
import time
pyautogui.keyDown("w")
time.sleep(2)
pyautogui.keyUp("w")
my output is "w"
but my output should be "wwwwwwwwwwwwwww" since I'm holding down the key?
the same thing occurs when im using the press function for pyautogui,
pyautogui.press("w") #but instead of pressing a single key, it totally just doesnt get outputted but only works for main keyboard functions like windowsKey and enter
if this is wrong, is their a way i can make it so I'm holding down the key?
From the Documentation it seems that it's not possible to do the way you have tried, however this function can help for 'holding down' a letter for a set number of seconds:
def hold_character(hold_time, character, interval=0.1):
pyautogui.write(character * int(hold_time / interval), interval=interval)
hold_character(2, 'w')
...gives the 'wwwwwwwwwwwwwww' effect for me

How to keep pressing certain key for certain amount of time in python?

I am trying to automate android game using python but I end up in a situation where I have to keep pressing CTRL key and use mouse wheel to zoom out.
I installed Pynput and tried this command
keyboard.press('a')
time.sleep(3)
keyboard.release('a')
But it doesn't keep pressing a key for 3 seconds but press only once.
Can anyone pls tell me a simple script, where it will keep pressing CTRL key and use mouse wheel to zoom out?
I'm assuming you want the key to be pressed over and over again rather than being held down (which is what I think your code above is doing).
You got two options that I know of. The easiest, by far, is to use floats alongside sleep, and do something like this:
timer = 0
while timer < 3:
time.sleep(0.1)
timer += 0.1
keyboard.press('a')
This will press the 'a' key every 0.1 seconds until 3 seconds is reached.
Otherwise, you could import the 'threading' module which lets you run code in paralel, and therefore run a loop and a timer simultaneously. This is probably a huge can of worms for what you're trying to do. The code below presses the 'a' key as fast as possible until the three second timer ends, it doesn't exit threads or anything though, which is why this is probably a bad approach:
global_timer = 0
def keep_pressing_a():
while global_timer <= 3:
keyboard.press('a')
def count_to_three():
global global_timer
keep_counting = True
while keep_counting:
time.sleep(1)
global_timer += 1
if global_timer >= 3:
keep_counting = False
threading.Thread(target=count_to_three).start()
threading.Thread(target=something).start()

How do I make get_pressed to work in pygame?

Despite hunting around I can't seem to find an answer to this seemingly simple question:
I'm new to pygame (but not to python), and am trying to get some code to work from continuous button presses - but get_pressed just does not seem to work for me. I made this just to check that I wasn't going insane (I've left out the importing to make it neat for you guys):
def buttonpress():
while True:
keys = pygame.key.get_pressed()
print keys[K_SPACE]
time.sleep(0.5)
buttonpress()
To the best of my knowledge, this should return a '1' when you press the space bar, but no matter what key you change it too - it simply returns an endless string of zeros.
What am I missing?
Thanks
There is no code that processes the input to get all the keys pressed. In order for this to work you need to call event.poll().
So your code will look like this.
import pygame
from pygame.locals import *
import time
pygame.init()
screen = pygame.display.set_mode((640,380))
def buttonpress():
while True:
keys = pygame.key.get_pressed()
print (keys[K_SPACE])
time.sleep(0.5)
pygame.event.poll()
buttonpress()
One more thing, do not use time.sleep(). This pauses the thread, and can cause the OS to think that your application does not respond (since it's not removing events from the event queue).

Categories

Resources