简体   繁体   English

拆分 b'' 在 Python3.7 中返回错误

[英]Splitting a b'' returns error in Python3.7

Currently I am writing a script in Python3.目前我正在用 Python3 编写脚本。 From that I will need to call a script which is written in Python2.从那以后,我需要调用一个用 Python2 编写的脚本。

I am doing this using subprocess doing the following:我正在使用subprocess执行以下操作:

>>> 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.只是为了澄清, arg1arg2可以有空格,这就是为什么我用逗号分隔命令的原因。

After that part has been run, output receives, clearly the output of the Python2 script.运行该部分后, output接收,显然是 Python2 脚本的输出。 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:但是,在调用>>> output.split('\\n')时,出现错误:

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

Also when trying >>> type(output) it returns <class 'bytes'> , which is only confusing me more.此外,在尝试>>> type(output)它返回<class 'bytes'> ,这只会让我更加困惑。

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.如你所见,如果你想拆分一个 bytes-like object,你需要传递一个 bytes-like object 作为参数。 Just change .split('\\n') to .split(b'\\n')只需将.split('\\n')更改为.split(b'\\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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