Looking for an efficient way to combine lines in Python
<p>I'm writing a program to aggregate strace output lines on a Linux host. When strace runs with the "-f" option it will intermix system calls line so:</p>

<pre><code>close(255 &lt;unfinished ...&gt;
&lt;... rt_sigprocmask resumed&gt; NULL, 8) = 0
&lt;... close resumed&gt; )       = 0
[pid 19199] close(255 &lt;unfinished ...&gt;
[pid 19198] &lt;... rt_sigprocmask resumed&gt; NULL, 8) = 0
[pid 19199] &lt;... close resumed&gt; )       = 0
</code></pre>

<p>I would like to iterate through the output and combine "unfinished" lines with "resumed" lines. So in the output above the following two lines:</p>

<pre><code>close(255 &lt;unfinished ...&gt;
.....
&lt;... close resumed&gt; )       = 0
</code></pre>

<p>Would be combined into:</p>

<pre><code>close(255) = 0
</code></pre>

<p>I was thinking about splitting the "unfinished" lines at ">" and putting that into a list. If a future line contained resume I would iterate through this list to see if the system call and pid are present. If they are I would split() the line at ">" and combine the two. Curious if there is a better way to do this?</p>

<p><strong>* Update *</strong></p>

<p>Thanks for the awesome feedback! I came up with the following and would love to get your thoughts on the code:</p>

<pre><code>holding_cell = list()

if len(sys.argv) &gt; 1:
    strace_file =  open(sys.argv[1], "r")
else:
    strace_file = sys.stdin

for line in strace_file.read().splitlines():
    if "clone" in line:
        print line
    if "unfinished" in line:
        holding_cell.append(line.split("&lt;")[0])
    elif "resumed" in line:
        # Get the name of the system call / pid so we  can try 
        # to match this line w/ one in the buffer
        identifier = line.split()[1]
        for cell in holding_cell:
            if identifier in cell:
                print cell + line.split("&gt;")[1]
                holding_cell.remove(cell)
    else:
        print line
</code></pre>

<p>Is there a more pythonic way to write this?  Thanks again for the awesome feedback!</p>

<p>Some iterators such as file objects can be nested. Assuming you are reading this from a file-like object, you could just create an inner loop to do the combining. I'm not sure what the formatting rules for <code>strace</code> logs are, but nominally, it could be something like</p>

<pre><code>def get_logs(filename):
    with open('filename') as log:
        for line in log:
            if "&lt;unfinished " in line:
                preamble = line.split(' ', 1)[0].strip()
                for line in log:
                    if " resumed&gt;" in line:
                        yield "{}) = {}\n".format(preamble,
                            line.split('=')[-1].strip())
                        break
             else:
                 yield line
</code></pre>

python