Silence music21 warnings

Viewed 261

I am getting an abundance of music21 warnings about zero-duration chords:

WARNING: midi chord with zero duration will be treated as grace

I tried overwriting the warn method on music21.environment.Environment() with the following:

def silence(*args, **kwargs): pass
e = music21.environment.Environment()
setattr(e, 'warn', silence)

I also tried muting all warnings:

import warnings
warnings.filterwarnings('ignore')

Neither has done the trick. How can I mute these (or ideally, all) warnings from music21? (I validate my data post-processing.)

2 Answers

If you're using ipython, you can try just muting the section you're trying to execute:

from IPython.utils import io

with io.capture_output():
    < ...your code... >

Otherwise, in the source code (~/Lib/site-packages/music21), you can navigate to midi/translate.py and adjust line 585-6 with a comment block or something similar to disable the warning.

enter image description here

Third option might be creating a context manager to mute printing, akin to the io.capture_output() function:

import io
import sys

class MuteWarn:
    def __enter__(self):
        self._init_stdout = sys.stdout
        sys.stdout = open(os.devnull, "w")
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._init_stdout

with MuteWarn():
    < ...your code... >

Try:

>>> from music21 import midi  # or your standard import
>>> def noop(input):
...   pass
... 
>>> midi.translate.environLocal.warn = noop

We're tracking a modernization request to move the warnings system over to the python warnings module at https://github.com/cuthbertLab/music21/issues/254 so that you can filter idiomatically. The case you've presented here is a bit more pressing than the original case on the ticket IMO, so I'll leave a comment.

Related