任务列表输出

时间:2012-11-23 09:11:44

标签: python python-3.x tasklist

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

我正在尝试使用tasklist,我想知道我能用它的输出做什么(比如将它设置为变量,数组,类似的东西)。

我正在使用Python 3.3,我在3.3找到文档时遇到了一些问题。

代码相对简单:

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

这会打印任务列表,但是我无法将该打印中的数据转换为变量。我假设它与Python有些微不足道,而与tasklist无关。

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

6 个答案:

答案 0 :(得分:5)

subprocess.check_output是最简单的:

(注意我在这里使用过ps,因为我对您所说的tasklist命令没有经验 - 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'

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

答案 1 :(得分: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'],
 ...

答案 2 :(得分:3)

基于其他一些答案...

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

答案 3 :(得分:0)

Python 3

let transformedFrame  = segmentView.layer.frame
let transformedBounds = segmentView.layer.bounds
let correctedBoundsX  = (transformedFrame.width - transformedBounds.width) / 2

segmentView.layer.bounds = CGRect(x: correctedBoundsX, y: transformedBounds.origin.y, width: transformedBounds.width, height: transformedBounds.height)

答案 4 :(得分: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)

答案 5 :(得分:0)

这是最终的解决方案。我试图找到一种方法来检查某个进程是否已经在运行,但是获取进程列表非常耗时。因此,我阅读了tasklist的文档,并得到/NH的意思是“无标题”和/FI进行过滤。 如果要查找所有进程,请使用cmd = 'tasklist /NH'

def get_running_processes(look_for='Music Caster.exe'):
    # 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)
    task = p.stdout.readline()
    while task != '':
        task = p.stdout.readline().decode().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
相关问题