3

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.)

duhaime
  • 25,611
  • 17
  • 169
  • 224

2 Answers2

4

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... >
Mark Moretto
  • 2,344
  • 2
  • 15
  • 21
3

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.

Jacob Walls
  • 873
  • 3
  • 15
  • Wonderful and idiomatic, thank you! It's really great how responsive you all are. For the record, this change did let other warnings from music21.midi.translate slip through--I was getting "TranslateWarning: Unable to determine instrument from ; getting generic UnpitchedPercussion". I was able to remove this latter warning by way of the warnings module: `import warnings; warnings.filterwarnings('ignore')`. Thank you again! – duhaime Sep 30 '21 at 19:01