So I'm trying to make a program that randomly places my mouse in specific areas in python, and I'm still testing it so it can get a bit crazy. I was wondering if it were possible to make a fail safe command that would terminate the program if the key or command were entered.
Since the program is clicking and moving around on another window on my computer it deselects the window python is running in, which make the "Keyboard Interrupt" fail to work.
Here's the program:
import pyautogui
import random
import time
time.sleep(6)#gives you time to click the right window
try:
while True:
x = random.randint(239, 1536) #randomizes the position of the mouse
pyautogui.moveTo(x,663) #moves the mouse to position
pyautogui.doubleClick() #fires the gun in game twise
time.sleep(1) #gives time for the game to
pyautogui.doubleClick() #catch up with the mouse and fires gun
pyautogui.doubleClick() #fires gun twice again
except KeyboardInterrupt:
print ('Yup')
And if there is anything wrong with the way I'm coding please tell me. I'm still new to coding so any tips would be awesome.
PyAutoGUI also has a fail-safe feature. Moving the mouse cursor to the upper-left corner
of the screen will cause PyAutoGUI to raise the pyautogui.FailSafeException
exception.
Your program can either handle this exception with try and except statements
or let the exception crash your program. Either way, the fail-safe feature will stop the
program if you quickly move the mouse as far up and left as you can.
>>>import pyautogui
>>>pyautogui.FAILSAFE= True
By default FAILSAFE is True, and you can also disable it.
>>>pyautogui.FAILSAFE = False
What you are looking to do is use a sys.exit() in your Exception.
Try this:
import sys
try:
# all your code
except KeyboardInterrupt:
sys.exit()
this should work, whenever you click the key it will break the loop, install the module keyboard with
pip install keyboard
if keyboard.is_pressed('q'):
break
Related
Hey I'm a beginner programmer, trying to write some code to press the letter 'k' on the keyboard every 4 seconds, while also being able to shut down the program with a keystroke WHILE IN A DIFFERENT WINDOW.
I've tried using this,
import time
import pyautogui
def kicker():
while True:
time.sleep(4)
pyautogui.press('k')
try:
while True:
kicker()
except KeyboardInterrupt:
pass
but I can only KeyboardInterrupt while the window I am coding in (jupyter notebook) is open, when I go into another window (with jupyter still open in the background) I can no longer interrupt the loop.
How can I make it so I can interrupt the loop on a keypress (not necessarily KeyboardInterrupt) while not on the jupyter notebook window?
You may want to use pyxhook to listen for all keystrokes on your machine. Do note that this is roughly the same as a keylogger and might involve admin access on your machine so there may be some safety concerns to think about.
Here is an example script from the repo that showcases it printing the event, but the line of interest is the function on line 15:
def kbevent(event):
global running
if event.Ascii == <...Put ascii code for k here...>:
running = False
I was hoping someone might have some insight on how to stop a script from continuing to repeat if a button is held (or in my case pressed longer than a second)?
Basically i've a button setup on the breadboard, and I have it coded to play an audio file when the button is pressed. This works, however if the button isn't very quickly tapped, then the audio will repeat itself until button is fully released. Also if the button is pressed and held, the audio file will just repeat indefinitely.
I've recorded a quick recording to demonstrate the issue if its helpful, here: https://streamable.com/esvoy6
I should also note that I am very new to python (coding in general actually), so its most likely something simple that I just haven't been able to find yet. I am using gpiozero for my library.
Any help or insight is greatly appreciated!
Here is what my code looks like right now:
from gpiozero import LED, Button
import vlc
import time
import sys
def sleep_minute(minutes):
sleep(minutes * 60)
# GPIO Pins of Green LED
greenLight = LED(17)
greenButton = Button(27)
# Green Button Pressed Definition
def green_btn_pressed():
print("Green Button Pressed")
greenButton.when_pressed = greenLight.on
greenButton.when_released = greenLight.on
# Executed Script
while True:
if greenButton.is_pressed:
green_btn_pressed()
time.sleep(.1)
print("Game Audio Start")
p = vlc.MediaPlayer("/home/pi/Desktop/10 Second Countdown.mp3")
p.play()
So from a brief look at it, it seems that 'time.sleep(.1)' is not doing what you are expecting. Ie. it is obviously interrupted by button presses. This is not abnormal behaviour as button presses on Ardiuno and raspPi (guessing here) would be processed as interrupts.
The script itself does not contain any prevention from double pressing or press and hold etc.
Have you put in any debug lines to see what is executing when you press the button?
I would start there and make adjustments based on what you are seeing.
I am not familiar with this gpiozero, so I can't give any insight about what it may be doing, but looking at the code and given the issue you are having, I would start with some debug lines in both functions to confirm what is happening.
Thinking about it for a minute though, could you not just change the check to 'if greenButton.is_released:'? As then you know the button has already been pressed, and the amount of time it is held in for becomes irrelevant. May also want to put in a check for if the file is already playing to stop it and start it again, or ignore and continue playing (if that is the desired behaviour).
Further suggestions:
For this section of code:
# Executed Script
while True:
if greenButton.is_pressed:
green_btn_pressed()
time.sleep(.1)
print("Game Audio Start")
p = vlc.MediaPlayer("/home/pi/Desktop/10 Second Countdown.mp3")
p.play()
You want to change this to something along these lines:
alreadyPlaying = 0
# Executed Script
while True:
if greenButton.is_pressed:
green_btn_pressed()
#Check if already playing file.
if alreadyPlaying == 1:
# Do check to see if file is still playing (google this, not sure off the top of head how to do this easiest).
# If file still playing do nothing,
#else set 'alreadyPlaying' back to '0'
break
#Check if already playing file.
if alreadyPlaying == 0:
time.sleep(.1)
print("Game Audio Start")
p = vlc.MediaPlayer("/home/pi/Desktop/10 Second Countdown.mp3")
p.play()
alreadyPlaying = 1
Hopefully you get the idea of what I am saying. Best of luck!
i think you have to write something like this in your loop:
import time, vlc
def Sound(sound):
vlc_instance = vlc.Instance()
player = vlc_instance.media_player_new()
media = vlc_instance.media_new(sound)
player.set_media(media)
player.play()
time.sleep(1.5)
duration = player.get_length() / 1000
time.sleep(duration)
Gets error when I click the exit (X) button:
Failed to execute script pong
How can I close the turtle game by clicking the exit button with no error?
Getting errors from turtle when you close the window is highly indicative of not playing by the rules event-wise. Typically it's due to a while True: loop instead of using timer events. A properly event-drive turtle program should reach the mainloop statement (or one of its equivalents) and allow events to run the show. If you want specifics, provide your code as part of your question.
The error in the terminal must be due to the the while True: loop that most beginners like me use. Closing the window abruptly stops the process while the while True: loop was still going on. So, in order to avoid this error you can define a function
#Function
def quit():
global running
running = False
#Keybinding
screen.onkeypress(quit, "q")
#Main game loop
while running:
...
#update events
...
Put simply, I'm trying to figure out how to run some code when the PyAutoGUI failsafe executes. I've tried searching this problem many times and can't figure out a way to do it.
This is what I want:
Move mouse to corner and provoke failsafe.
Right before program ends from fail safe, runs line of code.
Program completely closes.
The pyautogui.FailSafeException is raised when the mouse is moved to the upper left corner (x,y of 0, 0). You could catch this exception and run code from there:
import pyautogui
import sys
while True:
try:
pyautogui.moveTo() # Any PyAutoGUI (without side effects) call will do here.
except pyautogui.FailSafeException:
print('Running code before exiting.') # Your code here.
sys.exit()
Is there anyway for python 3 to recognise a keypress? For example, if the user pressed the up arrow, the program would do one thing whereas if the down arrow was pressed, the program would do something else.
I do not mean the input() function where the user has to press enter after the keypress , I mean where the program recognises the keypress as some as it was pressed.
Is this question too confusing? xD
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.
I assume this is a gui program,
If using the built-in gui module Tkinter, you can use bind to connect a function to a keypress.
main.bind('<Up>', userUpkey)
Where userUpKey is a function defined in the current scope.