3

我对 python 很陌生,但我无法找到我认为应该是一个相对简单的问题的答案。

我正在尝试使用tasklist,我想知道我可以用它的输出做什么(比如将它设置为变量、数组等)。

我正在使用Python 3.3,但在查找3.3.

代码比较简单:

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

这会打印任务列表,但我无法从该打印中获取数据到变量中。我假设它与 Python 无关,与任务列表无关。

最终,我希望制作任务列表条目的矩阵,这样我就可以搜索一个进程并获取相应的数据。

4

6 回答 6

6

根据其他一些答案...

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
于 2014-04-07T13:48:54.827 回答
5

subprocess.check_output是最简单的:

(注意我在ps这里使用过,因为我对tasklist您正在谈论的命令没有经验-尽管对窗口系统有参考...

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

然后你必须做一些事情才能res使用它......

于 2012-11-23T09:36:21.753 回答
4

os.system不是通常的 Python 命令。相反,它“调用”到更广泛的操作系统:os.system(foo)与进入命令行并键入foo. 这是从 Python 脚本执行任何程序的一种快速而肮脏的方式。

当然,有一些非快速和肮脏的方式来做到这一点。它们位于subprocess模块中,允许您启动任意子进程(其他程序)并与之通信,向其发送数据并接收其输出。

里面有一个快捷功能,它会调用一个外部程序,检查它是否成功,然后返回输出。该功能是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'],
 ...
于 2012-11-23T09:37:02.573 回答
0

这是最终的解决方案。我试图找到一种方法来检查进程是否已经在运行,但获取进程列表非常耗时。所以我阅读了文档tasklist并获得了/NH“无标题”和/FI过滤的含义。如果您正在寻找所有进程,请使用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
于 2020-11-01T17:38:27.427 回答
0

尝试这个:

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

示例代码:

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

输出:

['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']
...

更多的

例如,您可以添加一些条件。

info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.check_output('tasklist /v /fo csv', startupinfo=info)
于 2019-10-01T03:32:38.037 回答
0

蟒蛇 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()
于 2017-01-13T14:01:51.123 回答