You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境Python进程查杀报错:TypeError: a bytes-like object is required, not 'str'

解决Windows下Python查杀进程时的TypeError问题

错误原因

subprocess.check_output()默认返回字节流(bytes类型),你用字符串"myProcess.exe"直接和字节流做成员判断,类型不匹配导致报错:

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

三种可行解决方案

方案1:指定encoding参数直接返回字符串

Windows命令行默认编码为GBK,给check_output添加encoding='gbk'参数,让返回结果直接是字符串:

import os
import subprocess
from time import sleep

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

方案2:将判断字符串转为字节流

保持check_output的返回值为bytes,把判断用的字符串转为字节流(加b前缀):

import os
import subprocess
from time import sleep

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

方案3:使用universal_newlines=True参数(兼容旧版Python)

该参数会让check_output返回字符串,效果和指定encoding类似,适合Python 3.7及之前版本:

import os
import subprocess
from time import sleep

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

内容的提问来源于stack exchange,提问作者Willy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 02:37:07