简体   繁体   中英

Splitting a b'' returns error in Python3.7

Currently I am writing a script in Python3. From that I will need to call a script which is written in Python2.

I am doing this using subprocess doing the following:

>>> import subprocess
>>> my_command = 'python,script_in_py2.py,arg1,arg2'
>>> process = subprocess.Popen(my_command.split(','), stdout = subprocess.PIPE)
>>> output, error = process.communicate()

Just for clarification, arg1 and arg2 can have spaces that is why I am splitting the command by commas instead.

After that part has been run, output receives, clearly the output of the Python2 script. It looks something like:

b'output\\nOf\\nScript\\nIn\\nPython2\\nIs\\nHere\\n'

This looks like a bytes object to me. However when calling >>> output.split('\\n') , I am getting an error:

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

Also when trying >>> type(output) it returns <class 'bytes'> , which is only confusing me more.

Any ideas as to why is this happening?

The problem is not that the object you're trying to split is the wrong type, the problem is the delimiter you're trying to split by is not the same type as the thing you're trying to split.

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

>>>b'a\nb'.split(b'\n')
[b'a', b'b']

So as you can see, if you want to split a bytes-like object, you need to pass a bytes-like object as an argument. Just change .split('\\n') to .split(b'\\n')

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