Tasklist output

Tennesseej picture Tennesseej · Nov 23, 2012 · Viewed 14.8k times · Source

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.

Answer

Jon Clements picture Jon Clements · Nov 23, 2012

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