0

When trying to run the tasklist command with grep by using subprocess:

command = ("tasklist | grep edpa.exe | gawk \"{ print $2 }\"")
p = subprocess.Popen(command, stdout=subprocess.PIPE)
text = p.communicate(timeout=600)[0]
print(text)

I get this error:

ERROR: Invalid argument/option - '|'.
Type "TASKLIST /?" for usage.

It works fine when i run the command directly from cmd, but when using subprocess something goes wrong. How can it be fixed? I need to use the output of the command so i can not use os.system .

ASOLOMO
  • 49
  • 1
  • 5

2 Answers2

0

Two options:

  • Use the shell=True option of the Popen(); this will pass it through the shell, which is the part that interprets things like the |

  • Just run tasklist in the Popen(), then do the processing in Python rather than invoking grep and awk

Of the two, the latter is probably the better approach in this particular instance, since these grep and awk commands are easily translated into Python.

Your linters may also complain that shell=True is prone to security issues, although this particular usage would be OK.

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
0

In the absence of shell=True, subprocess runs a single subprocess. In other words, you are passing | and grep etc as arguments to tasklist.

The simplest fix is to add shell=True; but a much better fix is to do the trivial text processing in Python instead. This also coincidentally gets rid of the useless grep.

for line in subprocess.check_output(['tasklist'], timeout=600).splitlines():
    if 'edpa.exe' in line:
        text = line.split()[1]
        print(text)

I have assumed you really want to match edpa.exe literally, anywhere in the output line; your regex would match edpa followed by any character followed by exe. The code could be improved by doing the split first and then look for the search string only in the process name field (if that is indeed your intent).

Perhaps notice also how you generally want to avoid the low-level Popen whenever you can use one of the higher-level functions.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Really you'd want to do the `.split()` first, then match "edpa.exe" more specifically in the relevant column, so it doesn't match "edpa.exe" as anything other than the full name of the executable – Jiří Baum Jul 11 '21 at 08:09
  • 1
    Sure; many things could be improved in the OP's code, but I didn't want to second-guess what the output looks like on their OS or what exactly they _actually_ want. – tripleee Jul 11 '21 at 08:26