TypeError: 尝试迭代运行进程列表时需要一个类似字节的对象,而不是’str’。

huangapple go评论69阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月10日 21:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定