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?
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())
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With