Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading