how should the code look so the below script runs only between 06.30h and 8.00h??
best regards
#!/usr/bin/python
from time import strftime
import sys
import subprocess from subprocess
import Popen
import pifacedigitalio
from time import sleep
pfd = pifacedigitalio.PiFaceDigital() # creates a PiFace Digital
object testprocess = None
while strftime('%H:%M') >= '06:29':
while(True):
sleep(0.1)
if pfd.input_pins[0].value == 1 and not testprocess:
subprocess.Popen(["/bin/myscript"])
testprocess = Popen(["/bin/myscript1"])
if pfd.input_pins[0].value == 0:
if testprocess:
testprocess.kill()
testprocess = None
subprocess.Popen(["/bin/mycript"])
sleep(1)
if strftime('%H:%M') == '08:00':
sys.exit()
I would do it with something like this:
from time import strftime
import sys
while strftime('%H:%M') >= '18:00':
#Your code
if strftime('%H:%M') == '20:30':
sys.exit()
You can learn more about time module here: https://docs.python.org/2/library/time.html
just get time into a time struct and compute the number of minutes from midnight, test the time window in minutes:
lt = time.localtime()
minutes = 60*lt.tm_hour + lt.tm_min
if 60*6+30 <= minutes <= 60*8:
subprocess.Popen(["/bin/myscript"])
testprocess = Popen(["/bin/myscript1"])
Related
I want to loop my code when it reaches the end and move the set time forward by 2 hours whenever the code loops to beginning. How could I do it with existing code?
Editing the code as per 1st suggestion and adding loop:
import pynput
from datetime import datetime, timedelta
from threading import Timer
from pynput.keyboard import Key, Controller
import schedule
import time
count = 0
while count <3:
x=datetime.today()
y=x.replace(day=x.day+0, hour=16, minute=37, second=00, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+0.02
keyboard = Controller()
def bump():
keyboard.type("!d bump")
time.sleep (.1)
keyboard.press(Key.enter)
time.sleep (.1)
keyboard.release(Key.enter)
t = Timer(secs, bump)
t.start()
plus2 = x + timedelta(hours=2)
count +=1
t = Timer(secs, bump)
t.start()
This is my code yet. I am able to play the song in background and get input from the keyboard, but I can't stop the music process in the keyboard process. Even with that flag I couldn't managed to terminate process p.
import os
import sys
from playsound import playsound
import msvcrt
import threading
from ctypes import c_buffer, windll
from random import random
from time import sleep
from sys import getfilesystemencoding
import multiprocessing
file = open('toplay.txt')
to_listen = []
n = file.readline()
def Get_Path(name):
path = os.getcwd() + '\\' + name + ".mp3"
return path
for i in range (int(n)):
name = file.readline()
if i <= int(n)-2:
name = name[:-1]
to_listen.append(Get_Path(name))
flag = 0
def Check_Keyboard():
while True:
pressedKey = msvcrt.getch()
key = bytes.decode(pressedKey)
print(key)
if key == 's':
flag = 1
if __name__ == '__main__':
for i in range(int(n)):
p = multiprocessing.Process(target=playsound(to_listen[i],
False))
p.start()
q = multiprocessing.Process(target = Check_Keyboard)
q.start()
if flag == 1:
p.terminate()
Background: I'm using as Raspberry Pi rev 2 B to run a nature sound white noise generator of sorts that will randomly play audio tracks of varying length based on the time of night/morning. Some tracks are only a minute, some are several hours long. I'm looking for a way to check the time and change which type of sounds play based on time.
Current issue: I can start the appropriate audio for the time when the program first executes, but the timeloop execution stops polling once omxplayer starts up.
I have tried to call OMXPlayer without interrupting the time checker that determines what kind of audio to play, but once the audio playback starts I have been unable to continue checking time. Even if the play_audio() function wasn't recursive I would still like a way for the time checker to continue executing while the audio plays
#!/usr/bin/env python
import datetime, time, os, subprocess, random
from timeloop import Timeloop
from datetime import timedelta
from time import sleep
from omxplayer.player import OMXPlayer
from pathlib import Path
tl = Timeloop()
running_cycle = "off" # default value for the time cycle currently running
#function to check current time cycle
def check_time () :
dt_now = datetime.datetime.now()
t_now = dt_now.time()
t_night = datetime.time(hour=2,minute=0)
t_twilight = datetime.time(hour=4,minute=45)
t_morning = datetime.time(hour=7,minute=0)
t_end = datetime.time(hour=10,minute=0)
if t_night <= t_now < t_twilight:
return "night"
elif t_twilight <= t_now < t_morning:
return "twilight"
elif t_morning <= t_now < t_end:
return "morning"
else:
return "off"
# function that plays the audio
def play_audio (time_cycle):
subprocess.call ("killall omxplayer", shell=True)
randomfile = random.choice(os.listdir("/home/pi/music/nature-sounds/" + time_cycle))
file = '/home/pi/music/nature-sounds/' + time_cycle + '/' + randomfile
path = Path(file)
player = OMXPlayer(path)
play_audio (time_cycle)
# function that determines whether to maintain current audio cycle or play another
def stay_or_change():
global running_cycle
current_cycle = check_time()
if running_cycle != current_cycle:
if current_cycle == "off" :
player.quit()
else:
running_cycle = current_cycle
print "Now playing: " + running_cycle + " #{}".format(time.ctime())
play_audio(running_cycle)
#starts timeloop checker to play audio - works until stay_or_change() calls play_audio
#tl.job(interval=timedelta(seconds=10))
def job_10s():
print "10s job - running cycle: " + running_cycle + " - current time: {}".format(time.ctime())
stay_or_change()
# starts the timeloop
if __name__ == "__main__":
tl.start(block=True)
I have also tried running OMXPlayer with subprocess.run() but it still seems to hang up after the player starts. I'm completely open to any recommendations for background threading media players, process daemons, or time based execution methods.
I'm new to Python.
I had the recursion all wrong so it got caught in an infinite loop and the timeloop function wasn't really viable for this solution. Instead I had a function that played the sound, and then called the function that checked the time and plays from the appropriate sub-directory (or play nothing and wait).
Here's what I managed to come up with:
#!/usr/bin/env python
import datetime, time, os, subprocess, random
from datetime import timedelta
from time import sleep
from omxplayer.player import OMXPlayer
def check_time () :
dt_now = datetime.datetime.now()
t_now = dt_now.time()
t_night = datetime.time(hour=0,minute=0)
t_twilight = datetime.time(hour=5,minute=45)
t_morning = datetime.time(hour=7,minute=45)
t_end = datetime.time(hour=10,minute=0)
if t_night <= t_now < t_twilight:
return "night"
elif t_twilight <= t_now < t_morning:
return "twilight"
elif t_morning <= t_now < t_end:
return "morning"
else:
return "off"
def play_audio (time_cycle):
randomfile = random.choice(os.listdir("/home/pi/music/nature-sounds/" + time_cycle))
file = '/home/pi/music/nature-sounds/' + time_cycle + '/' + randomfile
print "playing track: " + randomfile
cmd = 'omxplayer --vol -200 ' + file
subprocess.call (cmd, shell=True)
what_to_play()
def what_to_play():
current_cycle = check_time()
if current_cycle == "off" :
print "sounds currently off - #{}".format(time.ctime())
time.sleep(30)
what_to_play()
else:
print "Now playing from " + current_cycle + " #{}".format(time.ctime())
play_audio(current_cycle)
what_to_play()
I've been trying to break a loop which is meant to look for a file in a certain location. My intention is to make my script look for that file for a certain time and then break whether the file is found or not but I can't get any idea.
How can I make the script wait for a certain time and then break when the time is up?
This is my script at this moment:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
while not os.path.exists(file_path):
time.sleep(1)
#is there any logic I can apply here to make the following line valid
# if waiting_time>=time_limit:break
print("Time's up")
Calculate the elapsed time by doing actual time minus start time by using time.time() function and assign a variable (file_exists in this code) which will be modified and check whether the file exist or not and use it for the loop.
As below:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
start = time.time()
file_exists = os.path.exists(file_path)
while not file_exists:
time.sleep(1)
file_exists = os.path.exists(file_path)
elapsed = time.time() - start
if elapsed >= time_limit:
break
else:
print("File exist.")
print(elapsed)
print("Time's up")
def exists_timeout(path, timeout):
"""Return once <path> exists, or after <timeout> seconds,
whichever is sooner
"""
timer = timeout
while (not os.path.exists(path)) and timer > 0:
time.sleep(1)
timer -= 1
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
cTime=0
time_limit = 5
while cTime<time_limit:
if os.path.exists(file_path)==False:
cTime=cTime+1
time.sleep(1)
else:
pass
if cTime==5:
responce="Time's Up"
else:
responce='Found'
print(responce)
As roganjosh commented, it would be simpler if you used time stamps. I have added relevant code below:
import os
import time
from datetime import datetime, timedelta
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = datetime.now() + timedelta(seconds=5)
present = datetime.now()
while (not os.path.exists(path)) and present < time_limit:
present = datetime.now()
if present >= time_limit:
print("Time's up")
break
time.sleep(1)
Here's how to do it with the threading.Timer() class. These can be configured to delay a specified amount of time and the call as function of your choosing.
import os
from threading import Timer
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
# Timer callback function.
def timeout():
global time_ran_out
time_ran_out = True
time_limit = 5
time_ran_out = False # Define variable the callback function modifies.
timer = Timer(time_limit, timeout) # Create a timer thread object.
timer.start() # Start the background timer.
while not os.path.exists(file_path):
time.sleep(1)
if time_ran_out:
print('Times up!')
break
print("Done")
To check for the availability of a file in a certain location you can try the following. The script will break as soon as the file is found otherwise it will wait upto 5 seconds for the file to be available before breaking.
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_to_wait = 5
time_counter = 0
while not os.path.exists(file_path):
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
print("done")
I'm trying to create a timer that starts when a condition for an if statement is met and then stops and returns the duration when elif condition is met, is this possible?
The purpose of the application is to send a true or false value to AWS IoT from an Android application. The Python script is subscribed to AWS and receives the value and uses it to determine whether the led should be on or off.
The code I have:
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import RPi.GPIO as GPIO
import sys
import logging
import time
from time import sleep
from timeit import default_timer as timer
import getopt
import grovepi
msgpay = None
# Custom MQTT message callback
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
global msgpay
msgpay = message.payload
led = 5
grovepi.pinMode(led, "OUTPUT")
start_time = timer()
if msgpay == "true":
print("turning on")
grovepi.digitalWrite(led, 1)
#time.sleep(3)
elif msgpay == "false":
print("turning off")
grovepi.digitalWrite(led, 0)
duration = timer() - start_time
print duration
Any help how to go about this would be appreciated.
Thanks