Python Forum

Full Version: python 3: TypeError: a bytes-like object is required, not 'str'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hey all,

i know this might be a dull question, but i dont get it...

this works in python2

#!/usr/bin/env python

import subprocess

proclist = subprocess.check_output(['ps', 'uaxw']).splitlines()
cfeagent_procs = [proc for proc in proclist if 'cf-agent' in proc]
cfeagent_count = len(cfeagent_procs)
print(cfeagent_count)
if cfeagent_count > 10:
    print("agents high")
Output:
root@aixhemadbprc2: /root # ./process_count.py 145 agents high
but not in python3

Error:
root@aixhemadbprc2: /root # ./process_count.py Traceback (most recent call last): File "./process_count.py", line 6, in <module> cfeagent_procs = [proc for proc in proclist if 'cf-agent' in proc] File "./process_count.py", line 6, in <listcomp> cfeagent_procs = [proc for proc in proclist if 'cf-agent' in proc] TypeError: a bytes-like object is required, not 'str'
sorry i need a hint...

wbr

chris
subprocess.check_output(['ps', 'uaxw']).splitlines()
Will output raw bytes because the encoding is missing.
This is the default behavior.

subprocess.check_output(['ps', 'uaxw'], encoding="utf8").splitlines()
Will decode as utf8 and return a str.

Docs: https://docs.python.org/3/library/subpro...eck_output
thank you!
Your code worked in Python 2 because strings were made up of bytes. In Python 3 strings are made up of Unicode characters. This is a good thing, but it does mean that you'll need to encode/decode when working with legacy software that still thinks ASCII is king.