python 3: TypeError: a bytes-like object is required, not 'str' - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: python 3: TypeError: a bytes-like object is required, not 'str' (/thread-34235.html) |
python 3: TypeError: a bytes-like object is required, not 'str' - wardancer84 - Jul-09-2021 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") but not in python3 sorry i need a hint...wbr chris RE: python 3: TypeError: a bytes-like object is required, not 'str' - DeaD_EyE - Jul-09-2021 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/subprocess.html#subprocess.check_output RE: python 3: TypeError: a bytes-like object is required, not 'str' - wardancer84 - Jul-09-2021 thank you! RE: python 3: TypeError: a bytes-like object is required, not 'str' - deanhystad - Jul-09-2021 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. |