[Tutor] While until the end of a list

Toni Fuente tonifuente at yahoo.co.uk
Tue Mar 14 07:20:13 EDT 2017


* Peter Otten <__peter__ at web.de> [2017-03-13 19:57:38 +0100]:
> 
> Toni Fuente via Tutor wrote:
> 
> > Hi,
> > 
> > I've got this script that goes through an httpd conf file, and gets the
> > related bits of it for a site, and writes a new config with values that
> > I am interested. The problem is that it finds the first chunk and
> > returns it, but I need to go to the end of all chunks list, because
> > there are also some chunks related to the same site that I need to
> > collect (virtualhost *:80 and virtualhost:443). I was
> > 
> > I was thinking in a while loop in the find_chunk function that will go
> > through all chunks and return the chunks that site is on, but I don't know
> > how to construct it.
> > 
> > Thank you in advance for any suggestion.
> 
> Currently the structure of your script seems to be
> 
> chunks = load_chunks()
> for site in get_sites():
>     interesting_chunk = find_chunk(site, chunks)
>     if interesting_chunk is not None:
>         do_stuff_with(interesting_chunk)
> 
> If I am understanding you correctly you want
> 
> chunks = load_chunks()
> for site in get_sites():
>     for interesting_chunk in find_chunks(site, chunks):
>         do_stuff_with(interesting_chunk)
> 
> 
> One way to make that work was already mentioned, have find_chunks return a 
> list:
> 
> def find_chunks(site, chunks):
>     matches = []
>     for chunk in chunks:
>         if any(site in line for line in chunk):
>             matches.append(chunk)
>     return matches

I've used the return list solution, that gave me a list of lists with the
different chunks, so I needed to convert it into a list of strings before I
could use it with the regular expression matching functions:

def new_chunk(chunk, user, site):
    config = []
    strings_chunk = list(itertools.chain.from_iterable(chunk))
    for item in strings_chunk:
        if "DocumentRoot" in item:
            root_dir = item.rsplit('/', 1)[-1]
            root_dir = root_dir.strip('\n')
            config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/[a-zA-Z\d-]{,63}', '/websites/' + user.rstrip() + '/' + site + '/' + root_dir, item))
            [...]

Thank you all for your help!


More information about the Tutor mailing list