Cecil Westerhof wrote:

> I want to get the first 6 lines of ps output. For this I use:
> ========================================================================
> from subprocess import check_output
> 
> ps_command = ('ps', '-eo', 'user,pid,pcpu,pmem,stat,start,time,cmd',
> '--sort') message = '\n'.join(check_output(ps_command +
> ('-%cpu',)).decode("utf-8").splitlines()[0:6])
> ========================================================================
> 
> It works, but does not look very efficient. Is there a better way to
> do this?

Efficiency be damned, readability counts ;)

With that in mind here's a little code cleanup:

 
import subprocess

def text_head(text, n):
    return "\n".join(text.split("\n", n)[:n])

def ps(sort=None):
    cmd = ['ps', '-eo', 'user,pid,pcpu,pmem,stat,start,time,cmd']
    if sort is not None:
        cmd += ["--sort", sort]
    return subprocess.check_output(cmd, universal_newlines=True)

if __name__ == "__main__":
    print(text_head(ps("-%cpu"), 6))

For long strings and small n text.split(\n", n)[:n] is a bit faster than 
text.splitlines()[n]

$ wc -l fodder.txt
969 fodder.txt
$ python3 -m timeit -s 'text = open("fodder.txt").read()' 'text.split("\n", 
6)[:6]'
100000 loops, best of 3: 7.54 usec per loop
$ python3 -m timeit -s 'text = open("fodder.txt").read()' 'text.splitlines()
[:6]'
1000 loops, best of 3: 215 usec per loop

but the effect on the total time to run the code should be negligable.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to