Check for regular expression in a list

Cecil Westerhof Cecil at decebal.nl
Fri May 26 09:12:58 EDT 2017


On Friday 26 May 2017 14:25 CEST, Jussi Piitulainen wrote:

> Rustom Mody <rustompmody at gmail.com> writes:
>
>> On Friday, May 26, 2017 at 5:02:55 PM UTC+5:30, Cecil Westerhof wrote:
>>> To check if Firefox is running I use:
>>> if not 'firefox' in [i.name() for i in list(process_iter())]:
>>>
>>> It probably could be made more efficient, because it can stop when
>>> it finds the first instance.
>>>
>>> But know I switched to Debian and there firefox is called
>>> firefox-esr. So I should use: re.search('^firefox', 'firefox-esr')
>>>
>>> Is there a way to rewrite
>>> [i.name() for i in list(process_iter())]
>>>
>>> so that it returns True when there is a i.name() that matches and
>>> False otherwise? And is it possible to stop processing the list
>>> when it found a match?
>>
>> 'in' operator is lazily evaluated if its rhs is an iterable (it
>> looks) So I expect you can replace if not 'firefox' in [i.name()
>> for i in list(process_iter())]: with if not 'firefox' in (i.name()
>> for i in list(process_iter())]):
>
> Surely that should be:
>
> if not 'firefox' in (i.name() for i in process_iter()):
>
> And that again should be:
>
> if any((i.name() == 'firefox') for i in process_iter()):
>
> Which can then be made into:
>
> if any(i.name().startswith('firefox') for i in process_iter()):

Thanks. I thought it better to use a function, so I wrote:
    def is_firefox_running():
        return any(process.name().startswith("firefox")
                   for process in process_iter())

I think it is a bit clearer to use:
    if is_firefox_running():

Also using the variable name i is not the best, so I changed it to
process.

Everyone thanks for the tips.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list