Splitting out the output of ps using Python

后端 未结 5 925
轻奢々
轻奢々 2020-11-30 07:58

On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START          


        
相关标签:
5条回答
  • 2020-11-30 08:22

    Check out the python.psutils package.

    psutil.process_iter returns a generator which you can use to iterate over all processes. p.cmdline is a list of each Process object's cmdline arguments, separated just the way you want.

    You can create a dictionary of pids vs (pid,cmdline,path) with just one line and then use it anyway you want.

    pid_dict = dict([(p.pid, dict([('pid',p.pid), ('cmdline',p.cmdline), ('path',p.path)]))
                     for p in psutil.process_iter()]))
    
    0 讨论(0)
  • 2020-11-30 08:23

    The maxsplit optional argument to the split method might help you:

    sep.split.(row, maxsplit=42)
    
    0 讨论(0)
  • 2020-11-30 08:30

    Here's a nice routine and usage to get you going:

    def getProcessData():
        ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
        processes = ps.split('\n')
        # this specifies the number of splits, so the splitted lines
        # will have (nfields+1) elements
        nfields = len(processes[0].split()) - 1
        retval = []
        for row in processes[1:]:
            retval.append(row.split(None, nfields))
        return retval
    
    wantpid = int(contents[0])
    pstats = getProcessData()
    for ps in pstats:
        if (not len(ps) >= 1): continue
        if (int(ps[1]) == wantpid):
            print "process data:"
            print "USER              PID       %CPU        %MEM       VSZ        RSS        TTY       STAT      START TIME      COMMAND"
            print "%-10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s  %s" % (ps[0], ps[1], ps[2], ps[3], ps[4], ps[5], ps[6], ps[7], ps[8], ps[9])
    
    0 讨论(0)
  • 2020-11-30 08:31

    Use the second parameter to split which specifies the maximum number of fields to split the string into. I guess you can find the number by counting the number of fields in the first line, i.e. the column titles.

    ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
    processes = ps.split('\n')
    # this specifies the number of splits, so the splitted lines
    # will have (nfields+1) elements
    nfields = len(processes[0].split()) - 1
    for row in processes[1:]:
        print row.split(None, nfields)
    
    0 讨论(0)
  • 2020-11-30 08:46

    Why don't you use PSI instead? PSI provides process information on Linux and other Unix variants.

    import psi.process
    for p in psi.process.ProcessTable().values(): …
    
    0 讨论(0)
提交回复
热议问题