How to exit loop on a keypress with python/osx? - python

I am on OSX.
I am importing opencv-python, so it might help; however, I am not showing anything, it's all command line off-screen processing.
While True:
do work ....
key = cv2.waitKey(1)
print key
The call to cv2.waitKey(1) consistently returns -1.
If I call cv2.imshow(..) before it, then it behaves correctly.
However, I have nothing to show, any chance I can still detect a keypress?
I need a keypress which isn't ctrl+c

Related

How do I break out of the loop at anytime with a keypress while in another window?

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

Is there a way to use cv2.waitkey() without showing the window?

I followed this program tutorial that captures the screen and puts it in a video file. The recording stops when the 'q' button is pressed. However, I didn't want to show the screen in a mini window and just write straight to the file. I am just calling the while loop shown in the tutorial except that I didn't include the part about showing the image to the 'Live' window. Now when I use:
while True:
img = pyautogui.screenshot()
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(np.array(frame))
# cv2.imshow('Live', frame)
if cv2.waitKey(1) == ord('q'):
print('done')
break
it won't detect my pressing q. What is going on here? When I press q the loop should stop right? I am just getting a 44 bit mp4 file as an end result from this. I think it might be because I didn't use imshow so waitkey won't do anything but I am not sure. Is there a way to get it to stop recording on a key press?
It's very likely that waitKey() doesn't do anything unless there's a window, since it's likely related to a window key event handler.
If you're on Windows, you could try msvcrt.kbhit(), which is a non-blocking call to request whether a key has been pressed on the console and could be read.
On other platforms, waiting for a keypress in a non-blocking manner might be non-trivial.
I think, you are right in assuming that since you didn't start the display(ie., cv2.imshow()) the cv2.watikey() doesn't work. Since your goal is to stop recording on key press I think you can follow this link's suggestion.
or try this pattern:
try:
while True:
break
#replace break with your code
except KeyboardInterrupt:
print("Press Ctrl-C to terminate while statement")
pass

How to keep an image open in OpenCV even if u press a key

How I do it? In matplotlib we have Show with False argument you can keep the image without closing. In my script, I pop out two images with cv2.imshow and I read that I can keep them up with waitKey(0), but when I press a key, they dissapear as the waitKey stablishs.
I want to know if there is a equivalent method for OpenCV as Show(False) from matplotlib.pyplot.
When you use waitKey(number), you are setting a timer for how long OpenCV should wait for any key to be pressed and will halt execution during that time until either a key is pressed or the timer is up. When you set number = 0, this is shorthand for saying wait forever until a key is pressed.
key = cv2.waitKey(0)
if key == 27:
cv2.destroyAllWindows()
The above code sets it so that when you press a key, it returns the key that you pressed to the variable: key. Now if key = 27 (i.e. the esacpe key has been pressed), then it will close the window. If not, then it will not. More details can be seen in the link below!
OpenCV Images
Cheers,
warning: if you are using a 64-bit machine, then you need to use
k = cv2.waitKey(0) & 0xFF
You can use a while loop:
while cv2.waitKey(0) != 27:
pass
The loop waits until Escape key is pressed.
Put it at the end of the script, because it's blocking the execution.

Run Upon PyAutoGUI Fail Safe

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()

How do I have a fail safe command in python

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

Categories