I'm trying to use Pynput to move my Minecraft character, but when I press run, it finishes without moving my character. I've retested it on stuff like the Minecraft chat and it works fine, I've also tested it on the Google Chrome search and it works, but weirdly not in Minecraft. My code is very simple.
from pynput.keyboard import Key, Controller
import time
myKeyboard = Controller()
time.sleep(3)
myKeyboard.press('w')
myKeyboard.release('w')
time.sleep(3)
myKeyboard.press('s')
myKeyboard.release('s')
I don't see anything wrong with my code and I don't know if pynput even works with moving Minecraft characters, or any characters for that matter.
According to pynput documentation, keeping a button pressed is best used with the pressed method and a with statement, like this:
with myKeyboard.pressed('w'):
time.sleep(3)
It should in theory hold the w key pressed for 3 seconds.
Related
I am newbie who wants to learn python. English is not my primary language, please ignore grammer error.
Here's my question.
In tradingview charts, i want to take screenshot, click down button, take screenshot again, wait for 3 second then go to next stock.
As i am newbie on python as well as stackoverflow if my any action fell dumb or wrong then please give me guidence.
Keyboard module (python) to control keyboard
first we need install a module name- keyboard in python
pip3 install keyboard
First, let's import the module:
import keyboard
Next, you can also simulate key presses using the send() function:
it will press space:
keyboard.send("space")
This will press and release the space button. In fact, there is an equivalent function press_and_release() that does the same thing.
You can also pass multi-keys:
keyboard.send("windows+d")
The + operator means we press both buttons in the same time, you can also use multi-step hotkeys:
send ALT+F4 in the same time, and then send space,
keyboard.send("alt+F4, space")
But what if you want to press a specific key but you don't want to release it ? Well, press() and release() functions comes into play:
press CTRL button
keyboard.press("ctrl")
release the CTRL button
keyboard.release("ctrl")
So this will press CTRL button and then release it, you can do anything in between, such as sleeping for few seconds, etc.
But now what if you want to write a long text and not just specific buttons ? send() would be inefficient. Luckily for us, write() function does exactly that, it sends artificial keyboard events to the OS simulating the typing of a given text, let's try it out:
keyboard.write("Python Programming is always fun!", delay=0.1)
Setting delay to 0.1 indicates 0.1 seconds to wait between keypresses, this will look fancy like in hacking movies!
Saving your problem
note- in windows 10, hot key for tacking screen shot is "windows+PrtScn.
Use your own hot key
from selenium import webdriver
import keyboard
import time
driver = webdriver.Chrome(executable_path="C:\\Users\\hp\\Desktop\\webcontrol\\chromedriver.exe")
driver.get("url ypu want to reach")
keyboard.send("windows+PrtScn")
keyboard.send("down")
keyboard.send("windows+PrtScn")
time.sleep(3)
driver.get("next stock url you want")
note- for going to next stock you can also use buttons or you can use selenium to click that particular stock
THANKS!
I'm trying to simulate a key being held down for a specific amount of time using python. I first tried using the keyboard module to accomplish this like so:
import time
import keyboard
keyboard.press('space')
time.sleep(5)
keyboard.release('space')
This block of code will correctly press the space key but not hold it down. It taps space and then instantly releases it before time.sleep(5) is called. The space key is pressed and released once, the program waits 5 seconds, then does nothing and exits. I also tried using the pynput module to accomplish this task like so:
import time
from pynput.keyboard import Key, Controller
keyboard = Controller()
keyboard.press(Key.space)
time.sleep(5)
keyboard.release(Key.space)
The same exact issue arises. Space is pressed and then instantly released instead of being held down. I also tried using the AHK module:
import time
from ahk import AHK
ahk = AHK()
ahk.key_down('Space')
time.sleep(5)
ahk.key_up('Space')
None of these modules have worked for me. I've tested all of them by opening up a blank notepad and then running the script.
So I've been working on a small project which will essentially be a macros program. The idea is to use a small external numpad with custom labels to click certain areas of the screen which correspond to buttons. I've got this all working beautifully with one minor (or major?) caveat which is the fact that I cannot differentiate between keyboards. Ideally I'd like to be able to still use my main keyboard and numpad normally. My code below for a sample key:
import keyboard
import pynput
from pynput.mouse import Button, Controller
import time
mouse = Controller()
tab = (1639, 16)
def handler():
print(keyboard.KeyboardEvent.device)
prev = mouse.position
mouse.position = tab
mouse.click(Button.left, 1)
mouse.position = prev
keyboard.add_hotkey("a", handler, suppress=True)
while True:
time.sleep(0.1)
So you can see here I am using the keyboard and pynput libraries. In the docs for the keyboard library, it notes an issue where on windows specifically, keyboard.KeyboardEvent.device returns "None" always.
I looked around a bit at various solutions for using raw input, but I wasn't able to really find anything applicable to my situation, and anything that looked remotely close was admittedly beyond my skill level. Anybody have any thoughts? Thanks.
I am trying to hold shift key and at the same time click with the mouse. I searched the internet and found a stackoverflow question about this. This is the post: Pyautogui - Need to hold shift and click
Also the code in this post was working for like three times!
Then suddenly it stopped working. It is really strange. I also tried it with pynput. Here is my post: Holding shift key + mouse click
It seems like holding shift and clicking the mouse are working seperately.
However, together it seems not to work
This is the code:
import pyautogui
import time
time.sleep(2)
pyautogui.keyDown('shift')
pyautogui.click()
pyautogui.keyUp('shift')
I am running on windows OS
It looks working fine?
Maybe use more keydown('shift') will make it
I will suggest you not to use pyautogui.
Its easy and simple with other modules. Install keyboard(for controlling keyboard) and mouse(for controlling mouse)
Here is a sample code that does what you want:
import keyboard, mouse #< Importing the required modules
keyboard.press("shift") #< Presses and holds the key
mouse.click("left") #< Makes Left click
keyboard.release("shift") #< Releases the held key
I wanted to write a program in Python for Windows that would act as a clicker, in which according to a key the user presses a click is made at a known location on the screen. This is used for an automated option selection from a list in a webpage. I have the clicking part working, but I wanted to be able to make several clicks during execution, as if there is a quiz with multiple lists one after another.
One option is to make a while loop with getch() from msvcrt. The thing is after a click outside the cmd its window is no longer selected, but rather the window where the destination point is located. Therefore, the script stops being active and the user cannot choose another location. A workaround is to click the cmd window to return the focus to it and be able to do any more clicks. To solve this, it would be necessary to create a service or, according to #Sanju, a thread.
The other option is to use a keylogger such as PyHook, which seems like the way to go. However, the problem is that the window where I want to use it in, a webpage in flash or another animations engine, causes an error that some users have found using this keylogger for example in Skype and is being described here. In my case, it also happens with this webpage and either when the click is made on the window itself or when the key is pressed with the window selected.
My base code is presented below, where click(...) would normally contain the coordinates as argument but they are being omitted for simplicity. In this case, 0 ends the program and there are three options being chosen with the numbers 1-3.
import msvcrt, win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
key=0
while key!=b'0':
key=msvcrt.getch()
if key==b'1':
click(...)
elif key==b'2':
click(...)
elif key==b'3':
click(...)
The attempts below try to implement #Sanju's suggestion, first with the whole while inside the thread and then with the queue, both not working as expected...
import threading, msvcrt, win32api, win32con
def MyThread():
key=0
while key!=b'0':
key=msvcrt.getch()
if key==b'1':
...
def click(x,y):
...
threading.Thread(target=MyThread,args=[]).start()
.
import queue, threading, msvcrt, win32api, win32con
def MyThread(key):
while key.get()!=b'0':
key.put(msvcrt.getch())
if key.get()==b'1':
...
def click(x,y):
...
key=queue.Queue()
key.put(0)
threading.Thread(target=MyThread,args=[key]).start()
The other attempt uses PyHook, but it's still facing the aforementioned issue.
import pyHook, pythoncom, win32api, win32con
def OnKeyboardEvent(event):
if event.Key=='Numpad1':
...
def click(x,y):
...
hm=pyHook.HookManager()
hm.KeyDown=OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
All you need here is move your click part to a thread and share the user input using a shareble object such as queue. It sounds like a overkill , but that's the way to keep your tasks in background.
And BTW, you have many GUI application frameworks available in Python like tkinter ,wxpython which can ease your objective.