3
votes

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.

6
What have to tried that is not working as you expect? - theAlse
Typing python 3.3 documentation into Google gives docs.python.org/3 as the first result... Also, no one will be able to help unless you say more about what tasklist is, and some example output from tasklist etc... - Jon Clements♦
Yeah I found the docs.python.org/3 website, but it doesn't have any documentation on tasklist. I don't know much about how tasklist works (that is kinda why I was here), I just know that it is part of the os module and the system function. I have seen it used on some other forums and got it to work with the code above, but it simply prints the output and I am trying to set that data to a variable. I guess a more direct question would be, how do you take something that has been printed and set it to a variable? - Tennesseej
As far as things I have tried so far. x = os.system("tasklist") That returned 0 x = 'os.system("tasklist")' That returned the string without running the function. Both of these I kinda expected, so I am kinda lost now as to what to try. - Tennesseej

6 Answers

5
votes

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
5
votes

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...

4
votes

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'],
 ...
0
votes

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()
0
votes

try this:

subprocess.check_output('tasklist /v /fo csv').decode(support_code_page).split('\n')[1:-1]

sample code:

def show_task_list():
    list_task = []
    for support_code_page in ('utf-8', 'cp950', 'cp932'):
        try:
            list_task = subprocess.check_output('tasklist /v /fo csv').decode(support_code_page).split('\n')[1:-1]
        except:
            continue
    if len(list_task) == 0:
        return None
    for string_proc in list_task:
        try:
            list_proc = eval('[' + string_proc + ']')
        except:
            continue
        # exe_name = list_proc[8]
        # print(exe_name)
        print([info for info in list_proc])

show_task_list()

output:

['System Idle Process', '0', 'Services', '0', '24 K', 'Unknown', 'NT AUTHORITY\\SYSTEM', '18:17:17', 'Not applicable']
['System', '4', 'Services', '0', '6,436 K', 'Unknown', '', '0:08:55', 'Not applicable']
...

More

you can add some condition for example.

info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.check_output('tasklist /v /fo csv', startupinfo=info)
0
votes

Here is the ultimate solution. I was trying to find a way to check if a process is already running but getting the list of processes was very time consuming. So I read the documentation for tasklist and got /NH meaning "No Header" and /FI for filtering. If you are looking for all processes use cmd = 'tasklist /NH'.

def get_running_processes(look_for):
    # edited from https://stackoverflow.com/a/22914414/7732434
    cmd = f'tasklist /NH /FI "IMAGENAME eq {look_for}"'
    p = Popen(cmd, shell=True, stdout=PIPE, stdin=DEVNULL, stderr=DEVNULL, text=True)
    task = p.stdout.readline()
    while task != '':
        task = p.stdout.readline().strip()
        m = re.match(r'(.+?) +(\d+) (.+?) +(\d+) +(\d+.* K).*', task)
        if m is not None:
            process = {'name': m.group(1), 'pid': m.group(2), 'session_name': m.group(3),
                       'session_num': m.group(4), 'mem_usage': m.group(5)}
            yield process


# sample usage
for process in get_running_processes():
    pass