From f4dc7199a4dafd755f2c9901b00e3ea89033867f Mon Sep 17 00:00:00 2001 From: Matthew Stratford Date: Thu, 8 Apr 2021 22:05:25 +0100 Subject: [PATCH] Some pep fixes. --- build/build-exe.py | 7 ++++--- player.py | 41 ++++++++++++++++++----------------------- player_handler.py | 9 ++++----- server.py | 10 +++++----- tests/test_player.py | 13 +++---------- websocket_server.py | 24 ++++++++++-------------- 6 files changed, 44 insertions(+), 60 deletions(-) diff --git a/build/build-exe.py b/build/build-exe.py index 259bcbc..cbded7e 100644 --- a/build/build-exe.py +++ b/build/build-exe.py @@ -1,4 +1,3 @@ -import sys import json file = open('build-exe-config.json', 'r') @@ -9,6 +8,8 @@ cmd_str = "pyinstaller " json_dests = ["icon_file", "clean_build"] pyi_dests = ["icon", "clean"] +filename = "" + for option in config["pyinstallerOptions"]: option_dest = option["optionDest"] @@ -24,9 +25,9 @@ for option in config["pyinstallerOptions"]: cmd_str += '--add-data "' + option["value"] + '" ' elif option_dest == "filenames": filename = option["value"] - elif option["value"] == True: + elif option["value"] is True: cmd_str += "--" + str(option_dest) + " " - elif option["value"] == False: + elif option["value"] is False: pass else: cmd_str += "--" + str(option_dest) + ' "' + str(option["value"]) + '" ' diff --git a/player.py b/player.py index fa8b730..cc86487 100644 --- a/player.py +++ b/player.py @@ -34,17 +34,14 @@ from pygame import mixer from mutagen.mp3 import MP3 from helpers.myradio_api import MyRadioAPI -from helpers.os_environment import isMacOS from helpers.state_manager import StateManager from helpers.logging_manager import LoggingManager -from helpers.types import PlayerState, RepeatMode from plan import PlanItem # TODO ENUM VALID_MESSAGE_SOURCES = ["WEBSOCKET", "UI", "CONTROLLER", "TEST", "ALL"] - class Player: out_q: multiprocessing.Queue last_msg: str @@ -84,7 +81,7 @@ class Player: def isInit(self): try: mixer.music.get_busy() - except: + except Exception: return False return True @@ -113,10 +110,10 @@ class Player: position: float = self.state.state["pos"] mixer.music.set_volume(0) mixer.music.play(0) - except: + except Exception: try: mixer.music.set_volume(1) - except: + except Exception: self.logger.log.exception( "Failed to reset volume after attempting loaded test." ) @@ -151,7 +148,7 @@ class Player: try: mixer.music.play(0, pos) self.state.update("pos_offset", pos) - except: + except Exception: self.logger.log.exception("Failed to play at pos: " + str(pos)) return False self.state.update("paused", False) @@ -162,7 +159,7 @@ class Player: def pause(self): try: mixer.music.pause() - except: + except Exception: self.logger.log.exception("Failed to pause.") return False @@ -175,7 +172,7 @@ class Player: position: float = self.state.state["pos_true"] try: self.play(position) - except: + except Exception: self.logger.log.exception( "Failed to unpause from pos: " + str(position) ) @@ -189,7 +186,7 @@ class Player: # if self.isPlaying or self.isPaused: try: mixer.music.stop() - except: + except Exception: self.logger.log.exception("Failed to stop playing.") return False self.state.update("pos", 0) @@ -206,7 +203,7 @@ class Player: if self.isPlaying: try: self.play(pos) - except: + except Exception: self.logger.log.exception("Failed to seek to pos: " + str(pos)) return False return True @@ -299,13 +296,13 @@ class Player: loaded_item = showplan[i] break - if loaded_item == None: + if loaded_item is None: self.logger.log.error( "Failed to find weight: {}".format(weight)) return False reload = False - if loaded_item.filename == "" or loaded_item.filename == None: + if loaded_item.filename == "" or loaded_item.filename is None: self.logger.log.info( "Filename is not specified, loading from API.") reload = True @@ -333,7 +330,7 @@ class Player: self.logger.log.info("Loading file: " + str(loaded_item.filename)) mixer.music.load(loaded_item.filename) - except: + except Exception: # We couldn't load that file. self.logger.log.exception( "Couldn't load file: " + str(loaded_item.filename) @@ -349,7 +346,7 @@ class Player: "length", mixer.Sound( loaded_item.filename).get_length() / 1000 ) - except: + except Exception: self.logger.log.exception( "Failed to update the length of item.") return False @@ -365,7 +362,7 @@ class Player: mixer.music.unload() self.state.update("paused", False) self.state.update("loaded_item", None) - except: + except Exception: self.logger.log.exception("Failed to unload channel.") return False return not self.isLoaded @@ -375,7 +372,7 @@ class Player: mixer.quit() self.state.update("paused", False) self.logger.log.info("Quit mixer.") - except: + except Exception: self.logger.log.exception("Failed to quit mixer.") def output(self, name: Optional[str] = None): @@ -390,7 +387,7 @@ class Player: mixer.init(44100, -16, 2, 1024, devicename=name) else: mixer.init(44100, -16, 2, 1024) - except: + except Exception: self.logger.log.exception( "Failed to init mixer with device name: " + str(name) ) @@ -407,8 +404,6 @@ class Player: def ended(self): loaded_item = self.state.state["loaded_item"] - stopping = True - # Track has ended print("Finished", loaded_item.name, loaded_item.weight) @@ -486,7 +481,7 @@ class Player: UPDATES_FREQ_SECS = 0.2 if ( - self.last_time_update == None + self.last_time_update is None or self.last_time_update + UPDATES_FREQ_SECS < time.time() ): self.last_time_update = time.time() @@ -503,7 +498,7 @@ class Player: response = custom_prefix else: response = "{}:{}:".format(self.last_msg_source, self.last_msg) - if msg == True: + if msg is True: response += "OKAY" elif isinstance(msg, str): if okay_str: @@ -570,7 +565,7 @@ class Player: ) self.seek(loaded_state["pos_true"]) - if loaded_state["playing"] == True: + if loaded_state["playing"] is True: self.logger.log.info("Resuming.") self.unpause() else: diff --git a/player_handler.py b/player_handler.py index 7111d78..4d94f4a 100644 --- a/player_handler.py +++ b/player_handler.py @@ -1,10 +1,9 @@ -from helpers.logging_manager import LoggingManager from setproctitle import setproctitle - -# from multiprocessing import current_process +from multiprocessing import current_process from time import sleep from os import _exit +from helpers.logging_manager import LoggingManager class PlayerHandler: logger: LoggingManager @@ -14,7 +13,7 @@ class PlayerHandler: self.logger = LoggingManager("PlayerHandler") process_title = "PlayerHandler" setproctitle(process_title) - # current_process().name = process_title + current_process().name = process_title try: while True: @@ -32,7 +31,7 @@ class PlayerHandler: ui_to_q[channel].put(message) if source in ["ALL", "CONTROLLER"]: controller_to_q[channel].put(message) - except: + except Exception: pass sleep(0.02) diff --git a/server.py b/server.py index 8645797..75615a0 100644 --- a/server.py +++ b/server.py @@ -467,9 +467,9 @@ def list_logs(): @app.route("/logs/") def send_logs(path): - l = open("logs/{}.log".format(path)) + log_file = open("logs/{}.log".format(path)) data = { - "logs": l.read().splitlines(), + "logs": log_file.read().splitlines(), "ui_page": "log", "ui_title": "Logs - {}".format(path), } @@ -610,14 +610,14 @@ def stopServer(): print("Stopping server.py") for q in channel_to_q: q.put("QUIT") - for player in channel_p: + for channel in channel_p: try: - player.join() + channel.join() except Exception as e: print("*** Ignoring exception:", e) pass finally: - del player + del channel del channel_from_q del channel_to_q print("Stopped all players.") diff --git a/tests/test_player.py b/tests/test_player.py index 9c8dbcc..0725aca 100644 --- a/tests/test_player.py +++ b/tests/test_player.py @@ -5,8 +5,6 @@ import time import os import json -from typing import List - from player import Player from helpers.logging_manager import LoggingManager @@ -17,6 +15,7 @@ TIMEOUT_QUIT_S = 10 test_dir = dir_path = os.path.dirname(os.path.realpath(__file__)) + "/" resource_dir = test_dir + "resources/" + # All because constant dicts are still mutable in python :/ def getPlanItem(length: int, weight: int): if length not in [1, 2, 5]: @@ -107,7 +106,7 @@ class TestPlayer(unittest.TestCase): return response[ len(source + ":" + msg) + 1 : ] # +1 to remove trailing : on source. - except Empty: + except Empty : pass finally: time.sleep(0.01) @@ -286,10 +285,4 @@ class TestPlayer(unittest.TestCase): # runs the unit tests in the module if __name__ == "__main__": - try: - unittest.main() - except SystemExit as e: - if e == True: - print("Tests failed :/") - else: - print("Tests passed!") + unittest.main() diff --git a/websocket_server.py b/websocket_server.py index 74fde96..b39109a 100644 --- a/websocket_server.py +++ b/websocket_server.py @@ -1,16 +1,15 @@ import asyncio from asyncio.futures import Future from asyncio.tasks import Task, shield - -from websockets.server import Serve -from helpers.logging_manager import LoggingManager import multiprocessing import queue -from typing import Any, Dict, List, Optional +from typing import List import websockets import json from os import _exit +from helpers.logging_manager import LoggingManager +from websockets.server import Serve class WebsocketServer: @@ -40,7 +39,8 @@ class WebsocketServer: try: asyncio.get_event_loop().run_forever() - except: + except Exception: + # Sever died somehow, just quit out. self.quit() def quit(self): @@ -52,7 +52,7 @@ class WebsocketServer: print("Deleting websocket server") self.quit() - async def websocket_handler(self, websocket, path): + async def websocket_handler(self, websocket, _): self.baps_clients.add(websocket) await websocket.send( json.dumps({"message": "Hello", "serverName": self.server_name}) @@ -65,7 +65,7 @@ class WebsocketServer: try: async for message in websocket: data = json.loads(message) - if not "channel" in data: + if "channel" not in data: # Didn't specify a channel, send to all. for channel in range(len(self.channel_to_q)): sendCommand(channel, data) @@ -74,11 +74,7 @@ class WebsocketServer: sendCommand(channel, data) async def send(conn, message): - # TODO this doesn't actually catch. - try: - await conn.send(message) - except: - pass + conn.send(message) await asyncio.wait( [send(conn, message) for conn in self.baps_clients] @@ -199,12 +195,12 @@ class WebsocketServer: try: message = message.split("OKAY:")[1] message = json.loads(message) - except: + except Exception : continue # TODO more logging elif command == "POS": try: message = message.split(":", 2)[2] - except: + except Exception : continue elif command == "QUIT": self.quit()