Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter a list using a lambda that raises exceptions

Using psutil I get a list of processes; I want to filter out those with a particular name.

filter(lambda p: p.name()=="x", psutil.process_iter())

However, the psutil.Process.name() function may throw... in that case filter gets the blow, and re-raises the exception to me.

Is there a filter_noexception kind of function/idiom, or do I need to wrap p.name() into an exception-swallowing function myself?

like image 987
xtofl Avatar asked Oct 20 '22 04:10

xtofl


2 Answers

You could do this :

def try_get_name(process_instance):
    try:
        return process_instance.name()
    except:
        return ""


filter(lambda p: try_get_name(p)=="x", psutil.process_iter())
like image 59
Raghav RV Avatar answered Oct 27 '22 11:10

Raghav RV


I added a replace_exception function decorator:

def replace_exception(original, default=None):
   def safe(*args, **kwargs):
       try:
          return original(*args, **kwargs)
       except:
          return default
   return safe

And now I can 'safeify' my function:

filter(replace_exception(lambda p: p.name()=="x"), psutil.process_iter())
like image 21
xtofl Avatar answered Oct 27 '22 09:10

xtofl