Check for regular expression in a list

Rustom Mody rustompmody at gmail.com
Fri May 26 07:47:45 EDT 2017


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())]):

As this sessions indicates

>>> def myiter():
...   yield 1
...   yield 2
...   print ("yielded 2")
...   yield 3
...   print("yielded 3")
... 

# basic behavior
>>> for x in myiter(): print(x)
... 
1
2
yielded 2
3
yielded 3

# does not reach 2 3
>>> 1 in myiter()
True

# reaches 2 but not the print after
>>> 2 in myiter()
True

# reaches 3 but not the print after
>>> 3 in myiter()
yielded 2
True

# exhausts the iterator
>>> 4 in myiter()
yielded 2
yielded 3
False
>>> 



More information about the Python-list mailing list