英文:
TypeError: a bytes-like object is required, not 'str' when trying to iterate over a list of running process
问题
我正在使用Python在Windows上。我试图在已经运行的情况下终止Windows进程,但我遇到以下错误:
TypeError: 需要类似字节的对象,而不是'str'
我导入了以下模块:
import os
import subprocess
from time import sleep
然后是我的代码:
s = subprocess.check_output('tasklist', shell=True)
if "myProcess.exe" in s:
print('myProcess.exe当前正在运行。正在终止...')
os.system('taskkill /f /im myProcess.exe')
sleep(0.5)
错误发生在条件语句中,当尝试比较进程"myProcess.exe"是否在列表s中时。
英文:
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.
答案1
得分: 1
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论