0

Im trying to execute the tasklist command using subprocess.check_output. Then taking that output (each PID) and adding it to a list.

The problem im having is that my list comprehension seems to be making the list for each digit in the PID rather than the entire PID.

Ive played around with it for a while now trying out various comprehensions ive found using google but cant get it working as id like. Im sure there's something stupid I'm doing wrong but as they "Its simple if you know how".

Any help would be appreciated

EXAMPLE OUTPUT

['1', '2', '4', '7', '2', '\n', '1', '3', '0', '2', '8', '\n']

CODE

>>> import subprocess
>>> cmd = 'cmd.exe /C tasklist| find "mstsc"| cut -d" " -f21'
>>> out = subprocess.check_output(cmd)
>>> tasklist = [task for task in out if task != None]
>>> print tasklist
['1', '2', '4', '7', '2', '\n', '1', '3', '0', '2', '8', '\n']
>>>
rpax
  • 4,468
  • 7
  • 33
  • 57
iNoob
  • 1,375
  • 3
  • 19
  • 47

1 Answers1

0

Looks like subprocess.check_output(cmd) returns a string rather than a list of strings, so you need to split() it to get the list you want to process using the comprehension:

import subprocess

cmd = 'cmd.exe /C tasklist| find "mstsc"| cut -d" " -f21'
out = subprocess.check_output(cmd).split('\n')
tasklist = [task for task in out if task != None]
print tasklist
cactus1
  • 629
  • 5
  • 8