0

This code prints out the tasklist of the OS. However, the following error is seen when it is run. Is there an easy solution to this problem?

  "mem_usage":int(m.group(5).decode('ascii', 'ignore'))})
ValueError: invalid literal for int() with base 10: '11,440'

Code:

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()
2
  • For what it's worth, if you want to list details about running processes in Python it would behoove you to use the very powerful psutil package. It works on Windows too! Commented Jun 23, 2018 at 19:57
  • A possible duplicate stackoverflow.com/questions/1779288/… Commented Jun 23, 2018 at 20:58

2 Answers 2

5

I haven't fully read your code, but from your error, I would suggest using the .replace method on the string that you are trying to convert to an integer to remove all commas.

For instance, at the moment, you are doing something like:

>>> int('123,456')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123,456'

which throws an error due to the comma marks. Simply remove all commas to fix this:

>>> int('123,456'.replace(',',''))
123456
Sign up to request clarification or add additional context in comments.

1 Comment

tasklist uses a strange comma formatting to print processes memory. removing the comma allows to get the proper value
0

See this:-

>>> int('23ds4') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '23ds4'

This is the same case as yours. That character "," is also not an integer in that provided string. So it is not a valid argument.

You better replace those commas from your integer contained string:-

>>> s = '11,234,234'
>>> s.replace(',','')
'11234234'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.