everything works except the next song doesn't play after the first is finished.
import os, random
from pygame import mixer
from pynput import keyboard
startup = 0
pause = 0
volume = 0.5
def Picker():
global startup
global volume
startup += 1
if startup > 1:
ThisSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
NextSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
ThisSong = NextSong
if ThisSong != NextSong:
mixer.init()
mixer.music.load("C:\\Users\\...\\Music" + ThisSong)
mixer.music.play(0)
mixer.music.set_volume(volume)
while mixer.music.get_busy():
def on_press(key):
global pause
global volume
if key == keyboard.KeyCode(char='-'):
volume -= 0.1
if volume < 0.1:
volume = 0.1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='='):
volume += 0.1
if volume > 1:
volume = 1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='['):
pause += 1
if pause == 1:
mixer.music.pause()
pause = 2
if pause == 3:
mixer.music.unpause()
pause = 0
with keyboard.Listener(on_press=on_press) as listener: listener.join()
else:
Picker()
else:
pass
Picker()
Picker()
screenshot of code
I can't get it to work, i'm very new to python so i'm probably missing something
obvious
Before starting: Thx #JGreenwell for copying the code.
Ok, so first, I’ll help you clean your code.
Things that are wrong
Having all that ThisSong and NextSong things: It won’t get saved when you restart Picker(). Either just have ThisSong, or place the ThisSong and NextSong assignment with the volume and pause variables:
.
pause = 0 # this is a problem! Next point
volume = 0.5
ThisSong = random.choice(...)
NextSong = random.choice(...)
The pause variable should be a boolean (True/False) and the pausing code should be like this:
.
pause = not pause
if pause:
# pause
else:
# unpause
Also, it would ideally be called paused
on_press and the Listener declaration should be outside the while loop, because otherwise they just keep being declared every time it loops. Then you should import time and put time.sleep(500) or something like that in the while loop, so that it doesn’t check every fraction of second.
As for the next song not playing, I don’t really know, but I’d suggest entering Picker() in the shell after the program has run (python -i script.py from CMD, IDLE leaves you in a shell by default). I would also suggest really following recommendation #3 as having them in the loop may break the loop and stop it from finishing. Most importantly, I would ask you to debug your code by adding print in every step of your code:
print(1)
if something:
print(2)
etc...
And seeing where it blocks
P.S.: The random dots are because you can’t have code in lists, so I had to exit the list.
Working solution, incase anyone else has the same problem as me in the future :)
from pygame import mixer
from pynput import keyboard
import threading
import random
import os
paused = 0
def player():
song = random.choice(os.listdir("C:\\users\\...\\desktop\\music"))
mixer.init()
mixer.music.load("C:\\users\\...\\desktop\\music\\" + song)
mixer.music.play(0)
while mixer.music.get_busy():
pass
else:
player()
def main():
t = threading.Thread(target = player, name = 'thread1', args = ())
t.start()
main()
def on_press(key):
global paused
if key == keyboard.KeyCode(char='['):
paused = not paused
if paused:
mixer.music.pause()
else:
mixer.music.unpause()
with keyboard.Listener(on_press=on_press) as listener: listener.join()
Related
I'm writing a script for game, i need to bind some key for pressing right click for three times. I can do it, but if i will use it in game i can press WASD or something else when i using hotkey and it doesn't work.
My code here :
import keyboard
import mouse
import time
iswork = False
def work():
global iswork
if iswork:
iswork = False
print("Script deactivated")
else:
iswork = True
print("Script activated")
keyboard.add_hotkey("F4",work)
def RRR():
if iswork :
for i in range(3):
mouse.right_click()
time.sleep(0.05)
bind = input("Bind for Right - Right - Right :")
#keyboard.add_hotkey(bind,RRR)
while iswork:
if keyboard.is_pressed("x") and len(keyboard._pressed_events) >= 1:
RRR()
elif keyboard.is_pressed("x"):
RRR()
while True :
count = 0
I want to write a bot that will simulate mouse movements when user is away for more than 5 minutes and stay put when user takes control i.e. moves the mouse.
I have written following code as a part of the program.
Here is the link to my old program which clicks at given points periodically. The problem with this program is I have to start the program when I want to go somewhere and after returning close the program in order to resume working.
Here is the one of the module I wrote for the new program which detects whether mouse is moving or not.
import win32api
from time import sleep
print("starting engine.")
count = 0
while(True):
savedpos = win32api.GetCursorPos()
if count>20*5:
break
sleep(1)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady.")
else:
print("Mouse is moving.")
count += 1
I wont be writing the code but I have the Idea to solve the problem
you use pyautogui.position() to keep checking the position and if it doesnt change position for 300 seconds you move it
I wrote following code referring other Stackoverflow posts.
This code waits 4 minutes for mouse being steady. Whenever mouse is moved, timer is reset to zero.
import win32api
from time import sleep
import pyautogui as gui
print("starting engine.")
count = 0
savedpos = win32api.GetCursorPos()
def actions():
print(gui.size())
while True:
#toast.show_toast("ROBOT V2 !", "Robot is active.", threaded=False, icon_path=None, duration=2)
gui.click()
gui.press('home')
gui.moveTo(541, 142, 0.25) # Money Transfer dropdown
gui.click()
sleep(0.5)
gui.moveTo(541, 172, 0.25) # Money Transfer link
gui.click()
sleep(5)
cond()
def cond():
count = 0
while True:
savedpos = win32api.GetCursorPos()
sleep(0.5)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady. Elapsed time: ", (count+1)/2, " seconds.")
count += 1
if count >= 480: # if count is greater than 60 it means timeout will occur after mouse is steady for more than
# 240 seconds i.e. 4 minutes. (approx.)
print("User away for more than 4 minutes, taking control of the system.")
actions()
break
else:
pass
else:
print("Mouse is moving.")
count = 0
cond()
I want to have a loop running that will print "Hello" and when I press "K" it stops printing but it doesn't end the program, then when I press "K" again it starts printing again.
I tried this(using the keyboard module):
import keyboard
running = True
while running == True:
print("hello")
if keyboard.is_pressed("k"):
if running == True:
running = False
else:
running = True
but when I press the button it just ends the program and that's not what I'm trying to do. I understand why it ends but I don't know how to make it not end. How can I do that?
import keyboard
running = True
display = True
block = False
while running:
if keyboard.is_pressed("k"):
if block == False:
display = not display
block = True
else:
block = False
if display:
print("hello")
else:
print("not")
Maybe something like that:
import keyboard
running = True
stop = False
while !stop:
if keyboard.is_pressed("k"):
running = !running # Stops "hello" while
if keyboard.is_pressed("q"):
stop = !stop # Stops general while
if running:
print("hello")
You could use a handler for the keypress, which sets an event that the main thread can then test for periodically, and wait if required.
(Note that there are two types of events here, the keypress event and the setting of the running, so these should not be confused.)
from threading import Event
from time import sleep
import keyboard
hotkey = 'k'
running = Event()
running.set() # at the start, it is running
def handle_key_event(event):
if event.event_type == 'down':
# toggle value of 'running'
if running.is_set():
running.clear()
else:
running.set()
# make it so that handle_key_event is called when k is pressed; this will
# be in a separate thread from the main execution
keyboard.hook_key(hotkey, handle_key_event)
while True:
if not running.is_set():
running.wait() # wait until running is set
sleep(0.1)
print('hello')
import sys
import keyboard
from time import sleep
running = True
while running:
if keyboard.is_pressed("k"):
sleep(1)
elif keyboard.is_presed('Esc'):
sys.exit()
else:
print("hello")
I didnt test it, so please give me feedback
I think the right way is flushing the buffer, because the previous solutions may print more. This works for windows, for Linux, you should refer to Python read a single character from the user
import time
import subprocess
import sys
import msvcrt
printing = True
while (1):
# Try to flush the buffer
while not msvcrt.kbhit() and printing:
print("hello")
doit = msvcrt.getch().decode('utf-8')
if doit=="k":
printing = not printing
print("stop/start")
if doit == 'q':
break
This is the output of this code:
Please note that, if you add print("stop/start") in Adrian Melon's program, you can see his program prints several time "hello" after 'k' is pressed until the buffer will be empty.
import keyboard
running = True
display = True
block = False
while running:
if keyboard.is_pressed("k"):
print("stop/start")
if block == False:
display = not display
block = True
else:
block = False
if display:
print("hello")
else:
pass
This is the output of #Adrian-Melon program:
import keyboard
running = True
display = True
block = False
while running:
if keyboard.is_pressed("space"):
if block == False:
display = not display
block = True
else:
block = False
if display:
print("hello")
else:
input("Press Enter to continue...")
if block == False:
display = not display
block = True
You can use this to stop and start again.
Im trying to move my Cursor every three seconds and if it went too far, reset it to its original location. I want the program to stop after I press any key on the keyboard.
It doesnt seem to work though... what could I be missing? This is what I came up with:
import win32api, win32con, time, sys, msvcrt
global z
z=10
def kbfunc():
#this is boolean for whether the keyboard has bene hit
x = msvcrt.kbhit()
if x:
sys.exit
else:
ret = False
return ret
def move(x,y):
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x/1920*65535.0), int(y/1080*65535.0))
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
kbfunc()
First, you need to install the keyboard module:
pip3 install keyboard
And than add it to your loop:
import keyboard
while True:
move(960,540+z)
time.sleep(3)
if z>100:
move(960,540)
z += -100
z + 10
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
I would guess that msvcrt.kbhit() does not store previous hits. It only tells you if a key is hit at the current moment in time. You can loop checking for keyboard hits. If no hits before 3 seconds, return:
import time
import msvcrt
import sys
def kbfunc(max_time=3):
start = time.time()
while not msvcrt.kbhit():
end = time.time()
if end - start >= max_time:
break
else:
sys.exit()
After trying around with the given answers, the finished solution looks like this:
global z
z=10
def move():
mouse.move(10, 10, absolute=False, duration=1)
def moveback():
mouse.move(-10, -10, absolute=False, duration=1)
while True:
move()
time.sleep(3)
moveback()
if keyboard.is_pressed('q'): # if key 'q' is pressed
break # finishing the loop
The goal of this script is to make a switch and let the user toggle it ON and OFF with a key press, and when the switch is ON, the script should execute a loop that print a message in the terminal. In another words, The goal is to repeatedly print a message when the switch is ON
Here is what i have tried:
import keyboard
import time
switch = 0 # The switch variable
def check_start():
global start
if keyboard.is_pressed("F5") and start == 0: # If F5 is pressed, turn ON print message loop
switch = 1
print(switch)
time.sleep(0.1) # This is to prevent the user toggling the switch too fast
if keyboard.is_pressed("F5") and start == 1: # If F5 is pressed again, turn OFF print message loop
switch = 0
print(switch)
time.sleep(0.1)
def print_name(): # If the switch is ON, it should print two seperate message with a 10 seconds interval
if start == 1:
print("start")
time.sleep(10)
print("end")
while True:
check_start()
print_name()
Here is the output of the script:
1
start
end
start
end
0
1
start
end
0
Now here's the problem:
The user cannot turn off the switch while the print loop is in progress. For example the user cannot turn off the script if the message "end" has not printed, the user can ONLY turn off the switch exactly after "end" has printed, and if the user has missed the opportunity to turn off the switch, he must wait 10 more seconds to turn it off. What i expected is the user can toggle On and OFF anytime s/he wishes to.
Is this possible to do in without importing too much module?
you can put an if condition inside your loop to do a break at a specific key
ex:
if keyboard.is_pressed("F5") and start == 1:
break
this would exit your infinite loop, although a more elegant code would work like this:
def check_start():
global start
if keyboard.is_pressed("F5") and start == 0:
#DO stuff
return True
if keyboard.is_pressed("F5") and start == 1:
#DO stuff
return False
while check_start():
print_name()
Here is a cleaner, more reliable approach using keyboard's built-in add_hotkey method.
Below is a simple program to toggle printing of the current timestamp.
import keyboard as kb
from datetime import datetime as dt
global print_flag
print_flag = False
def toggle_print():
global print_flag
print_flag = not print_flag
kb.add_hotkey('d', toggle_print)
while True:
timestamp = dt.now()
if print_flag:
print(timestamp)