python - 循环而不结束流
问题描述
我有一些 Python 代码,使用该代码我可以从我的 Google 日历中检索约会。该代码将每 15 分钟循环一次,并会在标题中查找带有特殊单词的约会。如果它找到一个事件,将启动一个音频流,它会在大约结束。活动结束后15分钟。这工作正常。
但是,由于 15 分钟的循环(time.sleep(900),音频流将被切断并重新开始。我不知道如何更改代码,所以它不会切断流,但会继续播放。我想我必须使用 If 构造(简单版本:如果找到事件并且 omxplayer = 播放,则跳过循环。
下面是我的代码。有谁能够帮我 ?
# Google Calendar API instellen en credentials.json opslaan
# https://developers.google.com/calendar/quickstart/go
# https://mediamagazine.nl/live-links-nederland/livestreams-nederland-landelijk/
from __future__ import print_function
import RPi.GPIO as GPIO
import datetime
import pickle
import os.path
import time
import os
import psutil
from subprocess import Popen
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
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 button_snooze(channel):
os.system('killall omxplayer.bin')
print("Snoozing")
def button_play(channel):
os.system('killall omxplayer.bin')
omxc = Popen(['omxplayer', '-b', 'http://playerservices.streamtheworld.com/api/livestream-redirect/RADIO538.mp3'])
print("Playing audiostream")
time.sleep(14400) # Play stream for 14400 seconds (4 hours).
def button_shutdown(channel):
os.system('killall omxplayer.bin')
time.sleep(3)
omxc = Popen(['omxplayer', '-b', '/home/pi/Music/shutting_down.mp3'])
print("Shutting down")
time.sleep(7)
#os.system("pkill -9 -f read_googlecalendar.py")
os.system("sudo shutdown -h now")
def main():
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
# Declare button to shutdown Raspberry Pi
# Don't forget to add a "1 kOhm" resistor between each pushbutton and GPIO pin or you'll fry your pins !!!
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(13,GPIO.RISING,callback=button_shutdown, bouncetime=2000)
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
timenow = str(datetime.datetime.now())
now = str(datetime.datetime.utcnow().isoformat()) + 'Z'
now_plus_1_minute = datetime.datetime.now() + datetime.timedelta(minutes = -119)
now_plus_1_minute_iso = now_plus_1_minute.isoformat() + 'Z'
print('Getting the upcoming events in 1 minute')
# Kalender primary aanpassen in andere kalender.
events_result = service.events().list(calendarId='primary', timeMin=now, timeMax=now_plus_1_minute_iso,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
print("Het is nu: " + timenow)
# Stop playing internetradio
os.system('killall omxplayer.bin')
print ("")
for event in events:
if event.has_key('summary'):
if 'Wakker' in event['summary']:
start = event['start'].get('dateTime', event['start'].get('date'))
print("Het is nu: " + timenow)
print ("")
print(start, event['summary'])
# Stop playing internetradio
#os.system('killall omxplayer.bin')
# Start playing internetradio
omxc = Popen(['omxplayer', 'http://playerservices.streamtheworld.com/api/livestream-redirect/RADIO538.mp3'])
print ("")
print ("=========================")
print ("")
#time.sleep(14400) # Play stream for 14400 seconds (4 hours).
while True:
if __name__ == '__main__':
main()
#time.sleep(300) # Wait 300 seconds (5 mins) and loop script.
#time.sleep(600) # Wait 600 seconds (10 mins) and loop script.
time.sleep(900) # Wait 900 seconds (15 mins) and loop script.
#time.sleep(10) # Wait 10 seconds and loop script.
print("==== REFRESH ====")
GPIO.cleanup()
解决方案
这是我的完整代码,现在它可以工作了。
# Google Calendar API instellen en credentials.json opslaan
# https://developers.google.com/calendar/quickstart/go
# https://mediamagazine.nl/live-links-nederland/livestreams-nederland-landelijk/
from __future__ import print_function
import RPi.GPIO as GPIO
import datetime
import pickle
import os.path
import time
import os
import psutil
from subprocess import Popen
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
player = False
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 button_snooze(channel):
os.system('killall omxplayer.bin')
print("Snoozing")
def button_play(channel):
os.system('killall omxplayer.bin')
omxc = Popen(['omxplayer', '-b', 'http://playerservices.streamtheworld.com/api/livestream-redirect/RADIO538.mp3'])
print("Playing audiostream")
time.sleep(14400) # Play stream for 14400 seconds (4 hours).
def button_shutdown(channel):
os.system('killall omxplayer.bin')
time.sleep(3)
omxc = Popen(['omxplayer', '-b', '/home/pi/Music/shutting_down.mp3'])
print("Shutting down")
time.sleep(7)
#os.system("pkill -9 -f read_googlecalendar.py")
os.system("sudo shutdown -h now")
def main():
global player
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
# Declare button to shutdown Raspberry Pi
# Don't forget to add a "1 kOhm" resistor between each pushbutton and GPIO pin or you'll fry your pins !!!
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(13,GPIO.RISING,callback=button_shutdown, bouncetime=2000)
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
timenow = str(datetime.datetime.now())
now = str(datetime.datetime.utcnow().isoformat()) + 'Z'
now_plus_1_minute = datetime.datetime.now() + datetime.timedelta(minutes = -119)
now_plus_1_minute_iso = now_plus_1_minute.isoformat() + 'Z'
print('Getting the upcoming events in 1 minute')
# Kalender primary aanpassen in andere kalender.
events_result = service.events().list(calendarId='primary', timeMin=now, timeMax=now_plus_1_minute_iso,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
print("Het is nu: " + timenow)
# Stop playing internetradio
os.system('killall omxplayer.bin')
player = False
print ("")
for event in events:
if event.has_key('summary'):
if 'Wakker' in event['summary']:
start = event['start'].get('dateTime', event['start'].get('date'))
print("Het is nu: " + timenow)
print ("")
print(start, event['summary'])
# Stop playing internetradio
#os.system('killall omxplayer.bin')
# Start playing internetradio
if (player != True):
omxc = Popen(['omxplayer', 'http://playerservices.streamtheworld.com/api/livestream-redirect/RADIO538.mp3'])
print ("")
print ("=========================")
print ("")
player = True
#time.sleep(14400) # Play stream for 14400 seconds (4 hours).
elif (player == True):
player = True
print ("speelt al")
while True:
if __name__ == '__main__':
main()
#time.sleep(300) # Wait 300 seconds (5 mins) and loop script.
#time.sleep(600) # Wait 600 seconds (10 mins) and loop script.
#time.sleep(900) # Wait 900 seconds (15 mins) and loop script.
time.sleep(10) # Wait 10 seconds and loop script.
print("==== REFRESH ====")
GPIO.cleanup()
推荐阅读
- neo4j - 在 cypher Neo4j 中处理嵌套的可选数据
- sql - oracle如何将各行的数据显示到一列?
- c - stdint.h include_next'd from stdint.h not found
- javascript - 如何防止表单提交,执行一些 JavaScript,然后在将数据传递到 NODE 时运行表单?
- angular - ngClass 最初不应用 css 类,仅在单击后
- firebase-cloud-messaging - FCM 到单个设备的最大消息速率
- c# - 参数 1:无法从 'System.Timespan' 转换为 'Instasharper.Classes.IRequestDelay'
- python - “它是如何找到 libpython 的?!” 谜
- c++ - 为函数 PlaySound 使用字符串变量
- c# - 如何将 SQL 查询转换为 LINQ