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.
By default,
subprocess.check_outputreturns abytesobject. The error you are seeing occurs when you check for membership of a string inbytes.For example:
results in:
You can fix this in 2 different ways, by passing in
text=Truetosubprocess.check_outputor by simply using abytesobject for membership checking.or: