简体   繁体   中英

Migrating from Python 2.7 to 3.8: "TypeError: a bytes-like object is required, not 'str'"

In one of the files I am seeing issue:

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

Code snippet:

def run_process(self, cmd):
        sh = self.is_win()
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=sh)
        output = child.communicate()[0].strip().split('\n')
        return output, child.returncode

Since you called subprocess.Popen() without text=True , Popen.communicate() returns bytes as documented, and you can't split bytes with a string. You can reproduce your error with the follow snippet:

>>> b'multi\nline'.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

One fix is to use split(b"\\n") . But since you're splitting on end of lines, I guess your command returns text, so the better solution is to pass text=True to subprocess.Popen() . The output of cmd will be decoded straight away, which will help see any encoding errors where you're best equipped to handle them.

Also, consider using subprocess.run() when the port to Python 3 is over as it's easier to use than subprocess.Popen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM