Trying to stop pygame but it can't because of interrupt - python

So I want it so when you click the x button on the top it stops the whole process but there is this "interrupt" error I keep getting and I tried multiple ways to stop the video, pygame or audio and none of them work. It just keeps printing in console interrupt.
import random
import psutil
import sys
from pygame.locals import *
from moviepy.editor import *
from pypresence import Presence
import time
pygame.init()
pygame.mixer.init()
pygame.display.set_caption('lofi hip hop radio - beats to relax/study to - v1.0')
def launch(movie):
clip = VideoFileClip(movie)
clip.preview()
def checkIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False;
def repeat():
running = True
clip = VideoFileClip("lofivid1.mp4")
time.sleep(5)
randomNumber = random.randint(1, 2)
print(str(randomNumber))
pygame.mixer.music.load("song" + str(randomNumber) + ".wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() and running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if(running):
clip.preview()
else:
pygame.quit()
exit(0)
while 1:
if checkIfProcessRunning('discord'):
client_id = 'ID CLIENT' #Put your client ID here
RPC = Presence(client_id)
RPC.connect()
print(RPC.update(state="Listening", details="Doing homework", large_image="https://static.actu.fr/uploads/2020/04/maxresdefault-960x640.jpg", small_image="https://static.actu.fr/uploads/2020/04/maxresdefault-960x640.jpg", large_text="LofiCli", start=time.time()))
else:
pass
repeat()
Every-time you click the x button you get this printed in console
Interrupt
And it does not close or change anything

Related

How to get out of a while loop with a specific key

I am trying to make an auto clicker but when i try to make my code exit it doesnt
here is my code
import mouse
import keyboard
import time
import os
os.system('cls')
def Config():
print("Click every")
hour = int(input("Hour: "))
minute = int(input("Minute: "))
second = int(input("Second: "))
total_time = hour*3600 + minute*60 + second
print("f6 to start and f10 to stop")
keyboard.wait('f6')
while True:
time.sleep(total_time)
mouse.click()
#def Fastest():
print(" Auto clicker!!!")
print(" By ze")
print("-------------------------")
print("Auto click on desired time or Fastest?")
choose = int(input("""
1. Config (No milliseconds)
2. Fastest
"""))
if choose == 1:
Config()
# elif choose == 2:
# Fastest()
#TODO:
# use mouse.click
# make it click with time
# make function fastest start with f1 and stops with f2
# create back up file
i tried an if statement with keyboard.is_pressed('key') thinking it would work but it doesnt my results are that the code exits (if key is pressed then exit)
You need to check if the key is pressed in your infinite loop. If it is pressed, you need to exit
while True:
time.sleep(total_time)
mouse.click()
if keyboard.is_pressed("f10"):
break
But this waits for the sleep function , so you'll need to hold f10 for total_time seconds.
You should use a loop to check for the key, rather than sleeping
import datetime
...
clicking = True
while clicking:
mouse.click()
s = datetime.datetime.now()
while ((datetime.datetime.now()-s).total_seconds() < total_time):
# This runs while the difference in time since you started the loop is less than the time you want to wait
if keyboard.is_pressed("f10"):
clicking = False
break
Use one thread to handle user input and another thread to do the clicking:
from threading import Thread
from msvcrt import getwch
import mouse
done = False
def auto_click():
print("Press \"q\" to quit")
global done
while True:
if getwch() == "q":
done = True
break
Thread( target = auto_click, daemon = True ).start()
while not done: # you can add whatever logic you want including a time gate here
mouse.click()

Python how to replace sleep with wait

I have a Python script where I would like to replace the sleep() with wait in order to interrupt the threads instantly even when they are sleeping.
However I don't know how to transform my functions into Events.
I read that asyncio could also be used but I am not sure to understand how it works.
Here is the code :
from pynput import keyboard
from pynput.keyboard import Key, Controller
import datetime
import time
import threading
import random
import pyautogui
from threading import Event
# --- functions ---
keyboardCtrl = Controller()
def run():
print('Running thread')
time.sleep(random.randrange(150,350)/1000)
while running:
my_keylist1=['e']
while len(my_keylist1) > 0:
n = random.choice(my_keylist1)
keyboardCtrl.press(n)
#print('Time:',datetime.datetime.now(),n)
my_keylist1.remove(n)
time.sleep(random.randrange(10200,10450)/1000)
print('Exiting thread 1')
def run2():
time.sleep(random.randrange(150,350)/1000)
while running:
pyautogui.keyDown('z')
#print('T2',datetime.datetime.now())
#time.sleep(random.randrange(1000,3000)/1000)
print('Exiting thread 2')
pyautogui.keyUp('z')
def run3():
time.sleep(random.randrange(150,350)/1000)
while running:
my_keylist1=['f']
while len(my_keylist1) > 0:
n = random.choice(my_keylist1)
keyboardCtrl.press(n)
#print('Time:',datetime.datetime.now(),n)
my_keylist1.remove(n)
time.sleep(random.randrange(6250,6550)/1000)
print('Exiting thread 3')
def on_press(key):
global running # inform function that it has to assign value to external variable
global clicker
global clicker2,clicker3
try: # PEP8: don't put it in one line - it make code unreadable for human
k = key.char
except:
k = key.name
if key == keyboard.KeyCode(char='q'):
print("Key Pressed")
if not running: # the same as `if running == False:`
print("Starting thread")
clicker = threading.Thread(target=run)
clicker2 = threading.Thread(target=run2)
clicker3 = threading.Thread(target=run3)
running = True # it has to be before `start()`
clicker.start()
clicker2.start()
clicker3.start()
else:
print("Stopping thread")
running = False # it has to be before `join()`
clicker.join()
clicker2.join()
clicker3.join()
# press `F1` to exit
if key == keyboard.Key.f1:
return False
# --- main ---
running = False # default value at start
try:
print("Starting program")
print("- press E to start/stop thread")
print("- press F1 to exit")
print("- press Ctrl+C to exit")
lis = keyboard.Listener(on_press=on_press)
lis.start()
print("Listening ...")
lis.join()
print("Exiting program")
except KeyboardInterrupt:
print("Stoped by Ctrl+C")
else:
print("Stoped by F1")
finally:
if running:
running = False
clicker.join()
clicker2.join()
clicker3.join()
Maybe you can try something like, I am sure there is a better solution, I would suggest reading the documentation.
import asyncio
from pynput import keyboard
from pynput.keyboard import Key, Controller
import datetime
import time
import threading
import random
import pyautogui
from threading import Event
# --- functions ---
keyboardCtrl = Controller()
async def run():
print('Running thread')
await asyncio.sleep(random.randrange(150, 350) / 1000)
while running:
my_keylist1 = ['e']
while len(my_keylist1) > 0:
n = random.choice(my_keylist1)
keyboardCtrl.press(n)
# print('Time:',datetime.datetime.now(),n)
my_keylist1.remove(n)
#time.sleep(random.randrange(10200, 10450) / 1000)
await asyncio.sleep(random.randrange(10200, 10450) / 1000)
print('Exiting thread 1')
async def run2():
#time.sleep(random.randrange(150, 350) / 1000)
await asyncio.sleep(random.randrange(150, 350) / 1000)
while running:
pyautogui.keyDown('z')
# print('T2',datetime.datetime.now())
# time.sleep(random.randrange(1000,3000)/1000)
print('Exiting thread 2')
pyautogui.keyUp('z')
async def run3():
#time.sleep(random.randrange(150, 350) / 1000)
await asyncio.sleep(random.randrange(150, 350) / 1000)
while running:
my_keylist1 = ['f']
while len(my_keylist1) > 0:
n = random.choice(my_keylist1)
keyboardCtrl.press(n)
# print('Time:',datetime.datetime.now(),n)
my_keylist1.remove(n)
#time.sleep(random.randrange(6250, 6550) / 1000)
await asyncio.sleep(random.randrange(6250, 6550) / 1000)
print('Exiting thread 3')
async def on_press(key):
global running # inform function that it has to assign value to external variable
global clicker
global clicker2, clicker3
try: # PEP8: don't put it in one line - it make code unreadable for human
k = key.char
except:
k = key.name
if key == keyboard.KeyCode(char='q'):
print("Key Pressed")
if not running: # the same as `if running == False:`
print("Starting thread")
#await run()
#await run2()
#await run3()
await asyncio.gather(*[run(), run2(), run3()])
#clicker = threading.Thread(target=run)
#clicker2 = threading.Thread(target=run2)
#clicker3 = threading.Thread(target=run3)
running = True # it has to be before `start()`
#clicker.start()
#clicker2.start()
#clicker3.start()
else:
print("Stopping thread")
running = False # it has to be before `join()`
#clicker.join()
#clicker2.join()
#clicker3.join()
# press `F1` to exit
if key == keyboard.Key.f1:
return False
# --- main ---
running = False # default value at start
def main(*args, **kwargs):
asyncio.run(on_press(args[0]))
try:
print("Starting program")
print("- press E to start/stop thread")
print("- press F1 to exit")
print("- press Ctrl+C to exit")
lis = keyboard.Listener(on_press=main)
lis.start()
print("Listening ...")
lis.join()
print("Exiting program")
except KeyboardInterrupt:
print("Stoped by Ctrl+C")
else:
print("Stoped by F1")
finally:
if running:
running = False
#clicker.join()
#clicker2.join()
#clicker3.join()

How to stop/resume a loop without having to terminate the terminal?

This is a small macro for a game.
I would like to stop the program (NOT close it!) with the F9 key and then when I click F9 again, it will resume. If possible without having to exit the game.
F9 - Start/Stop the program
import pyautogui
import time
import keyboard
print("Press F10 to stop and F9 to start")
while keyboard.is_pressed('f10') == False:
if keyboard.is_pressed('f9') == True:
time.sleep(3)
pyautogui.press('w')
time.sleep(1)
pyautogui.press('s')
time.sleep(1)
pyautogui.press('w')
time.sleep(1)
pyautogui.press('s')
time.sleep(1)
pyautogui.press('a')
time.sleep(4)
pyautogui.press('t')
you can use pynput to monitor the keyboard
from time import sleep
from threading import Thread
from pynput.keyboard import Key, Listener, Controller
def on_press(key):
if key == Key.f9: # start and stop the macro
flags['running'] = not flags['running']
elif key == Key.f10: # closes the program
flags['exit'] = True
return False # stop the listener
def macro(flags):
keyboard = Controller()
while not flags['exit']:
if flags['running']: # your macro here
sleep(3)
keyboard.type('w')
# etc...
flags = {'running' : True, 'exit' : False}
macro_thread = Thread(target=macro, args=(flags,))
macro_thread.start()
# Collect events until released
with Listener(on_press=on_press) as listener:
listener.join()
macro_thread.join()
if you want the code to stop immediately you need to change the sleeps inside the macro function:
from time import time
def check_exit(s, flags):
""" checks if the exit flag becomes true for s seconds """
start = time()
while time() < (start + s):
if flags['exit']:
return True
return False
def macro(flags):
keyboard = Controller()
while not flags['exit']:
if flags['running']:
if check_exit(3, flags): return
keyboard.type('w')
# etc...

How to output while waiting for a character input in Python 3?

I want to make a timer which requiers space press to stop it. I also want to print out how much time has passed since the start of the loop. I tried this:
import msvcrt
import time
print("Press space")
start_time = time.time()
while True:
# print how much time has passed
print(start_time - time.time(), end='\r')
# break the loop if space btn was pressed
if msvcrt.getch() == b" ":
break
But the problem is that the time passed will be printed only if I pressed a key, and I want it to print out continuesly. I tried this solution from https://stackoverflow.com/a/22391379/12132452, but because it was python 2, i kept getting this error
Traceback (most recent call last):
File "f:/Projects/Python/test.py", line 9, in <module>
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failed
What do I need to do?
This might help:
import sys
import keyboard
import time
print("Press space")
start_time = time.time()
while True:
try:
print(start_time - time.time(), end='\r')
if keyboard.is_pressed('SPACE'):
print("\nyou pressed SPACE, exiting...")
sys.exit()
except:
break
I know this question was answered, but here is another way of doing it in pygame:
import pygame
import time
pygame.init()
wn = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Timer')
start_time = time.time()
def main():
running = True
fps = 60
clock = pygame.time.Clock()
while running:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
print(time.time() - start_time)
running = False
pygame.display.update()
main()
Also, to install pygame open a terminal and type:
python -m pip install pygame==1.9.6

Pygame : force playing next song in queue even if actual song isn't finished? (aka "Next" button)

I want to make with pygame the same functionalities as a walkman : play, pause , queuing is ok.But how to do the previous/next buttons?
How can I ,with pygame, force the play of the next song which has been queued (and pass the ong which is actually playing?)
Have a list of song titles, and keep track of where you are in the list with a variable. Whether you are using pygame.mixer.music or pygame.mixer.Sound, when the "next" button is clicked, just have the variable change by one, and then stop the song, and have song the variable corresponds to play instead.
Code example for pygame.mixer.Sound:
#setup pygame above this
#load sounds
sound1 = pygame.mixer.Sound("soundone.ogg")
sound2 = pygame.mixer.Sound("soundtwo.ogg")
queue = [sound1, sound2] #note that the list holds the sounds, not strings
var = 0
sound1.play()
while 1:
if next(): #whatever the next button trigger is
queue[var].stop() # stop current song
if var == len(queue - 1): # if it's the last song
var = 0 # set the var to represent the first song
else:
var += 1 # else, next song
queue[var].play() # play the song var corresponds to
This was an example i got working for myself to wrap my head around the behavior of the program.
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' # noqa This is used to hide the default pygame import print statement.
import pygame
import time
# Credit: https://forums.raspberrypi.com/viewtopic.php?t=102008
pygame.mixer.init()
pygame.display.init()
screen = pygame.display.set_mode((420, 240)) # Shows PyGame Window.
playlist = list()
playlist.append('/Music/Tom MacDonald - Angels (Explicit).mp3')
playlist.append('/Music/Falling In Reverse - Bad Girls Club (Explicit).mp3')
pygame.mixer.music.load(playlist.pop()) # Get the first track from the playlist
pygame.mixer.music.queue(playlist.pop()) # Queue the 2nd song
pygame.mixer.music.set_endevent(pygame.USEREVENT) # Setup the end track event
pygame.mixer.music.play() # Play the music
running = True
while running:
time.sleep(.1)
for event in pygame.event.get():
if event.type == pygame.USEREVENT: # A track has ended
if len(playlist) > 0: # If there are more tracks in the queue...
pygame.mixer.music.queue(playlist.pop()) # Queue the next one in the list
elif event.type == pygame.QUIT: # Create a way to exit the program.
running = False

Categories