Search code examples
pythonwindowstaskkill

TypeError: a bytes-like object is required, not 'str' when trying to iterate over a list of running process


I am using Python in Windows. I am trying to kill a windows running process if it is already running but i get below error:

TypeError: a bytes-like object is required, not 'str'

I import the following modules:

import os
import subprocess
from time import sleep

Then below my code:

s = subprocess.check_output('tasklist', shell=True)
if "myProcess.exe" in s:
    print('myProcess.exe is currently running. Killing...')
    os.system("taskkill /f /im myProcess.exe")
    sleep(0.5)

The error happens just in the conditional when trying to compare if the process myProcess.exe is in the list s.


Solution

  • By default, subprocess.check_output returns a bytes object. The error you are seeing occurs when you check for membership of a string in bytes.

    For example:

    'foo' in b'bar'
    

    results in:

    TypeError: a bytes-like object is required, not 'str'
    

    You can fix this in 2 different ways, by passing in text=True to subprocess.check_output or by simply using a bytes object for membership checking.

    s = subprocess.check_output('tasklist', shell=True, text=True)
    

    or:

    if b"myProcess.exe" in s:
        # do something