Skip to content

Commit

Permalink
Use more pythonic logging
Browse files Browse the repository at this point in the history
  • Loading branch information
R. Kevin Nelson committed May 2, 2016
1 parent 00f8980 commit 508859d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 41 deletions.
58 changes: 25 additions & 33 deletions Oe2sSLE_GUI.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
import tkinter.filedialog
import tkinter.messagebox
import tkinter.ttk
#import re

import argparse
import logging
import math
import platform
import threading
#import time
import warnings
import sys

Expand All @@ -44,6 +45,11 @@

Oe2sSLE_VERSION = (0,0,9)

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug",
help="Debug to the console instead of a log file",
action="store_true")

# for pyIntaller bundled executable
def resource_path(relative_path):
try:
Expand All @@ -53,29 +59,6 @@ def resource_path(relative_path):

return os.path.join(base_path, relative_path)

class logger:
def __init__(self):
self.file = None
self.stderr = sys.stderr
self.stdout = sys.stdout
sys.stderr=self
sys.stdout=self

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.write('-- Logger closed --\n')
self.file.close()
sys.stderr = self.stderr
sys.stdout = self.stdout

def write(self, data):
if not self.file:
self.file = open('Oe2sSLE.log', 'a')
self.file.write(data)
self.file.flush()

class WaitDialog(tk.Toplevel):
def __init__(self, parent, *args, **kwargs):
Expand Down Expand Up @@ -1383,7 +1366,7 @@ def reset_vars(self):
self.tuneVal.set(esli.sampleTune)
self.samplingFreq.set(esli.samplingFreq)
if fmt.samplesPerSec != esli.samplingFreq:
print("Warning: sampling frequency differs between esli and fmt")
logging.warn("sampling frequency differs between esli and fmt")
self.duration.set("{:.4f}".format(len(data)/fmt.avgBytesPerSec if fmt.avgBytesPerSec else 0))
self.stereo.set(fmt.channels > 1)
self.smpSize.set(len(data))
Expand Down Expand Up @@ -2109,10 +2092,19 @@ def _on_down(event):

if __name__ == '__main__':
# redirect outputs to a logger
with logger() as log:
# Create a window
app = SampleAllEditor()
playIcon=tk.PhotoImage(file=resource_path("images/play.gif"))
stopIcon=tk.PhotoImage(file=resource_path("images/stop.gif"))
app.mainloop()
audio.terminate()
# Create a window
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s:%(filename)s(%(lineno)d)%(funcName)s: %(message)s")
else:
logging.basicConfig(filename="Oe2sSLE.log",
level=logging.DEBUG,
format="%(asctime)s %(levelname)s:%(filename)s(%(lineno)d)%(funcName)s: %(message)s")
logging.info("-- begin logging")
app = SampleAllEditor()
playIcon=tk.PhotoImage(file=resource_path("images/play.gif"))
stopIcon=tk.PhotoImage(file=resource_path("images/stop.gif"))
app.mainloop()
audio.terminate()
logging.info("-- done logging")
2 changes: 1 addition & 1 deletion RIFF/smpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,4 @@ def __setattr__(self, name, value):
self.__dict__[name] = value


#TODO: easily add loop(s)
#TODO: easily add loop(s)
21 changes: 14 additions & 7 deletions e2s_sample_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
along with Oe2sSLE. If not, see <http://www.gnu.org/licenses/>
"""

import logging
import struct
import RIFF
import warnings
Expand Down Expand Up @@ -158,6 +159,7 @@ def __setitem__(self, index, value):


def __init__(self, file=None, chunkHeader=None):
logging.debug("Initializing RIFF class")
self.fields = dict()
self.rawdata = bytearray(RIFF_korg_esli._dataSize)
offset = 0
Expand Down Expand Up @@ -255,28 +257,30 @@ def __setattr__(self, name, value):
self.__dict__[name] = value

def read(self, file, chunkHeader):
logging.debug("trying to read RIFF file")
if chunkHeader.id != b'esli':
raise TypeError("'elsi' chunk expected")
if chunkHeader.size < RIFF_korg_esli._dataSize:
raise ValueError('Unknown esli chunck size')
if chunkHeader.size > RIFF_korg_esli._dataSize:
print ('Unusual esli chunck size')
logging.warn('Unusual esli chunck size')
self.rawdata[:] = file.read(chunkHeader.size)
if len(self.rawdata) != chunkHeader.size:
raise EOFError('Unexpected End Of File')

if self._16_22_UFix != b'\x00\x00\x00\x7F\x00\x01\x00\x00\x00\x00\x00\x00':
print('Unusual values in _16_22_UFix: ', self._16_22_UFix)
logging.warn('Unusual values in _16_22_UFix: %s', self._16_22_UFix)
if self._27_UFix != b'\x00':
print('Unusual values in _27_UFix: ', self._27_UFix)
logging.warn('Unusual values in _27_UFix: %s', self._27_UFix)
if self._35_3C_UFix != b'\x00\x00\x00\x00\x00\x00\x00':
print('Unusual values in _35_3C_UFix: ', self._35_3C_UFix)
logging.warn('Unusual values in _35_3C_UFix: %s', self._35_3C_UFix)
if self._43_48_UFix != b'\x01\xB0\x04\x00\x00':
print('Unusual values in _43_48_UFix: ', self._43_48_UFix)
logging.warn('Unusual values in _43_48_UFix: %s', self._43_48_UFix)
if self._4C_UFix != b'\x00':
print('Unusual values in _4C_UFix: ', self._4C_UFix)
logging.warn('Unusual values in _4C_UFix: %s', self._4C_UFix)
if self.useChan0_UFix != 1:
print('Unusual value in useChan0_UFix: ', self.useChan0_UFix)
logging.warn('Unusual value in useChan0_UFix: %s', self.useChan0_UFix)
logging.debug("done with 'read'")

def reset(self):
self._16_22_UFix = b'\x00\x00\x00\x7F\x00\x01\x00\x00\x00\x00\x00\x00'
Expand Down Expand Up @@ -399,6 +403,7 @@ def load(self, filename):
self.samples.append(sample)
except:
self._loadErrors += 1
logging.warn('Recovering from an error while reading a sample')
warnings.warn('Recovering from an error while reading a sample')
traceback.print_exc()

Expand All @@ -411,6 +416,7 @@ def save(self, filename):
for sample in self.samples:
addr=sample.RIFF.chunkList.get_chunk(b'korg').data.chunkList.get_chunk(b'esli').data.OSC_0index
if riffAddrs[addr][1] is not None:
logging.warn('Multiple samples with same OSC number, duplicates lost')
warnings.warn('Multiple samples with same OSC number, duplicates lost')
riffAddrs[addr] = (riffNextAddr,sample)
riffNextAddr+=len(sample)
Expand All @@ -424,6 +430,7 @@ def save(self, filename):
if riffAddr[0]:
diff = riffAddr[0]-f.tell()
if diff:
logging.warn('empty feeling')
warnings.warn('empty feeling')
f.write(b'\x00'*diff)
riffAddr[1].write(f)

0 comments on commit 508859d

Please sign in to comment.