0

The standard Unix utilities like lsof and ps produce output in a fixed width format with a header which should be easy to ingest programmatically.

Alas, the existing answers to How to efficiently parse fixed width files? require me to specify the column widths in advance instead of inferring then from the header line.

So, what is the right way to ingest the output of ps and lsof (and their ilk) into Python?

Community
  • 1
  • 1
sds
  • 58,617
  • 29
  • 161
  • 278
  • 1
    Don't look to parsing output from system utilities if [psutil](https://pypi.python.org/pypi/psutil) covers what you want... – Jon Clements Nov 20 '16 at 17:21

1 Answers1

0

Here is what I used until I switched to psutil:

import subprocess

def lsof ():
    with subprocess.popen(["lsof"],stdout=subprocess.PIPE) as fd:
        header = fd.readline().split()
        for line in fdout:
            return [dict(zip(header,line.split())) for line in fd]

Warning: this ignores the possibility of spaces in the lsof output fields!

sds
  • 58,617
  • 29
  • 161
  • 278