Press a key in a batch script with Python - 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)

Related

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?

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

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.

ipython shell - how to emulate an enter press

I would like to exit the ipython shell, i.e. type %exit then hit enter, when the escape key is pressed. I can successfully type "%escape" in the shell, but am having difficulty figuring out the "enter" press.
ref: https://ipython.readthedocs.io/en/latest/config/details.html#keyboard-shortcuts
Code in a .py file in the startup folder:
from prompt_toolkit.key_binding import KeyBindings
from IPython import get_ipython
ip = get_ipython()
def exit_ipy(event):
buffer = event.current_buffer
buffer.insert_text('%exit') # just need to figure out how to insert an "enter" press after
buffer.accept_action.validate_and_handle(event.cli, buffer) # I thoght this may work?
ip = get_ipython()
registry = ip.pt_app.key_bindings
registry.add_binding(u'escape')(exit_ipy)
This should do the trick :
import pyautogui
from prompt_toolkit.key_binding import KeyBindings
from IPython import get_ipython
ip = get_ipython()
def exit_ipy(event):
buffer = event.current_buffer
buffer.insert_text('%exit')
pyautogui.press('enter') # simulates an enter press
ip = get_ipython()
registry = ip.pt_app.key_bindings
registry.add_binding(u'escape')(exit_ipy)
pyautogui let you simulate a key press exactly like if you did it yourself, so I think that this solution will work
PS: I CAN NOT TEST THIS SO I DID NOT

How to open a program using keyboard input?

My project is to make a program that you can run while you are playing games or other programs in the background.
When you press a certain key, your notepad should open and also close after you press the same key again.
I have managed to open notepad with subprocess and that works fine but I have no idea to make it open only when a certain key is pressed.
Thanks for any help!
EDIT:
What I tried already:
import subprocess
import keyboard
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
input()
here it just doesn't detect any keyboard input, the input() at the end makes the program not close instantly
import subprocess
import keyboard
keyboard.add_hotkey('ctrl+k', print,args=("hello", "test"))
input()
Here if I press "ctrl+k it" will print hello test that means the hotkey works fine. When I switch this part "print,args=("hello", "test")" to "subprocess.Popen('C:\Windows\System32\notepad.exe')"(it should open the program instead of printing hello test) the notepad opens instantly after I run the program and when I press "ctrl+k" I get a big error.
A more complex, but still working example could be the following. With this code your program will be always listening the keyboard, not only when you are focused on the input, so may be mre practical in your case
from pynput import keyboard
import subprocess
import threading
class MyException(Exception): pass
class Listening:
"""Is allways waiting for the keyboard input"""
def __init__(self):
self.notepad_open = False # to know the state
with keyboard.Listener(
on_press=self.on_press) as listener:
try:
listener.join()
except:
pass
def on_press(self, key):
try:
if key.char == "k":
if not self.notepad_open:
self.subprocess = \
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
self.notepad_open = True # update state
else:
self.subprocess.kill()
self.notepad_open = False # update state
except: # special key was pressed
pass
thread = threading.Thread(target=lambda: Listening())
thread.start()
The problem is that you check for the key 'k' only once at the beginning. If you want the program to correctly work then you should try this:
import time
import subprocess
import keyboard
while True:
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
time.sleep(5)
-I used the time so that you can only open the program once 5 seconds(If you're curious, see what happens without it)-

How do I get key pressed?

I was wondering how do I get a key pressed in python
I tried doing:
import msvcrt as keys
while True:
key = keys.getch()
if key == "a":
print("You have pressed a")
Does anyone know how to fix it?
This might help you:
import msvcrt
while True:
if msvcrt.kbhit() and msvcrt.getch() == chr(97): # chr(97) = 'a'
print("You have pressed a")
Note: your code and my code won't work in many Python IDE's! You need to execute the python file, e.g. in a command window.

Categories

Resources