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()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 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](https://psutil.readthedocs.io/en/latest/) package. It works on Windows too! – Iguananaut Jun 23 '18 at 19:57
  • A possible duplicate https://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-tho – DYZ Jun 23 '18 at 20:58

2 Answers2

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
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
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'
Vicrobot
  • 3,795
  • 1
  • 17
  • 31