-->

Tasklist output

2019-02-25 11:50发布

问题:

I am pretty new to python, but I am unable to find an answer to what I am thinking should be a relatively simple issue.

I am trying to utilize tasklist, and I am wondering what I can do with the output of it (like set it to a variable, an array, things like that).

I am using Python 3.3, and I have had some trouble finding documentation on 3.3.

The code is relatively simple:

import os
os.system("tasklist")
input()

This prints the tasklist, but I have had trouble getting data from that print into variables. I am assuming it's something minor to do with Python, and not to do with tasklist.

Ultimately I am looking to make a matrix of the tasklist entries, that way I can search for a process, and grab the corresponding data.

回答1:

subprocess.check_output is the easiest:

(Note I've used ps here, as I'm not experienced with the tasklist command you're talking about - there's reference to it for window systems though...)

>>> import subprocess
>>> res = subprocess.check_output(['ps'])
>>> res
'  PID TTY          TIME CMD\n 1749 ?        00:00:00 gnome-keyring-d\n 1760 ?        00:00:00 gnome-session\n 1797 ?        00:00:00 ssh-agent\n 1800 ?        00:00:00 dbus-launch\n 1801 ?        00:00:04 dbus-daemon\n 1814 ?        00:00:09 gnome-settings-\n 1819 ?        00:00:00 gvfsd\n 1821 ?        00:00:00 gvfs-fuse-daemo\n 1829 ?        00:11:51 compiz\n 1832 ?        00:00:00 gconfd-2\n 1838 ?        00:00:29 syndaemon\n 1843 ?        00:34:44 pulseaudio\n 1847 ?        00:00:00 gconf-helper\n 1849 ?        00:00:00 gvfsd-metadata\n 1851 ?        00:00:00 bluetooth-apple\n 1852 ?        00:00:04 nautilus\n 1853 ?        00:00:01 nm-applet\n 1855 ?        00:00:00 polkit-gnome-au\n 1856 ?        00:00:00 gnome-fallback-\n 1873'

Then you have to do something on res so it's usable...



回答2:

os.system isn't a usual Python command. Instead, it "calls out" to the wider operating system: os.system(foo) is roughly the same as going to a command line and typing foo. It's a quick-and-dirty way of executing any program from a Python script.

There are, of course, non-quick and dirty ways of doing this. They are found in the subprocess module, and allow you to start up an arbitrary subprocess (other program) and communicate with it, sending it data and receiving its output.

There's a quick shortcut function in there which will call an external program, check whether it succeeded, and return the output. That function is subprocess.check_output:

In[20]: [line.split() for line in subprocess.check_output("tasklist").splitlines()]
Out[20]: 
[[],
 ['Image', 'Name', 'PID', 'Session', 'Name', 'Session#', 'Mem', 'Usage'],
 ['=========================',
  '========',
  '================',
  '===========',
  '============'],
 ['System', 'Idle', 'Process', '0', 'Services', '0', '24', 'K'],
 ['System', '4', 'Services', '0', '308', 'K'],
 ['smss.exe', '352', 'Services', '0', '1,628', 'K'],
 ['csrss.exe', '528', 'Services', '0', '7,088', 'K'],
 ['wininit.exe', '592', 'Services', '0', '6,928', 'K'],
 ['csrss.exe', '600', 'Console', '1', '79,396', 'K'],
 ['services.exe', '652', 'Services', '0', '19,320', 'K'],
 ...


回答3:

Based on a few of the other answers...

import subprocess
import re    
def get_processes_running():
    """ Takes tasklist output and parses the table into a dict

    Example:
        C:\Users\User>tasklist

        Image Name                     PID Session Name        Session#    Mem Usage
        ========================= ======== ================ =========== ============
        System Idle Process              0 Services                   0         24 K
        System                           4 Services                   0     43,064 K
        smss.exe                       400 Services                   0      1,548 K
        csrss.exe                      564 Services                   0      6,144 K
        wininit.exe                    652 Services                   0      5,044 K
        csrss.exe                      676 Console                    1      9,392 K
        services.exe                   708 Services                   0     17,944 K
        lsass.exe                      728 Services                   0     16,780 K
        winlogon.exe                   760 Console                    1      8,264 K

        # ... etc... 

    Returns: 
        [   {'image': 'System Idle Process', 'mem_usage': '24 K', 'pid': '0', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'System', 'mem_usage': '43,064 K', 'pid': '4', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'smss.exe', 'mem_usage': '1,548 K', 'pid': '400', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'csrss.exe', 'mem_usage': '6,144 K', 'pid': '564', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'wininit.exe', 'mem_usage': '5,044 K', 'pid': '652', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'csrss.exe', 'mem_usage': '9,392 K', 'pid': '676', 'session_name': 'Console', 'session_num': '1'}, 
            {'image': 'services.exe', 'mem_usage': '17,892 K', 'pid': '708', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'lsass.exe', 'mem_usage': '16,764 K', 'pid': '728', 'session_name': 'Services', 'session_num': '0'}, 
            {'image': 'winlogon.exe', 'mem_usage': '8,264 K', 'pid': '760', 'session_name': 'Console', 'session_num': '1'},
            #... etc... 
        ]

    """
    tasks = subprocess.check_output(['tasklist']).split("\r\n")
    p = []
    for task in tasks:
        m = re.match("(.+?) +(\d+) (.+?) +(\d+) +(\d+.* K).*",task)
        if m is not None:
            p.append({"image":m.group(1),
                        "pid":m.group(2),
                        "session_name":m.group(3),
                        "session_num":m.group(4),
                        "mem_usage":m.group(5)
                        })
    return p


回答4:

Python 3

# -*- coding: utf-8 -*-

import re

from subprocess import Popen, PIPE, check_output

def get_processes_running():
    """
    Takes tasklist output and parses the table into a dict
    """
    tasks = check_output(['tasklist']).decode('cp866', 'ignore').split("\r\n")
    p = []
    for task in tasks:
        m = re.match(b'(.*?)\\s+(\\d+)\\s+(\\w+)\\s+(\\w+)\\s+(.*?)\\s.*', task.encode())
        if m is not None:
            p.append({"image":m.group(1).decode(),
                        "pid":int(m.group(2).decode()),
                        "session_name":m.group(3).decode(),
                        "session_num":int(m.group(4).decode()),
                        "mem_usage":int(m.group(5).decode('ascii', 'ignore'))
                        })
    return( p)

def test():
    print(*[line.decode('cp866', 'ignore') for line in Popen('tasklist', stdout=PIPE).stdout.readlines()])

    lstp = get_processes_running()
    for p in lstp:
        print(p)
    return

if __name__ == '__main__':
    test()