How do I convert a string to a buffer in Python 3.1?

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I am attempting to pipe something to a subprocess using the following line:

p.communicate("insert into egg values ('egg');");  TypeError: must be bytes or buffer, not str 

How can I convert the string to a buffer?

回答1:

The correct answer is:

p.communicate(b"insert into egg values ('egg');"); 

Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:

value = open('thefile', 'rt').read() p.communicate(value); 

The change that to:

value = open('thefile', 'rb').read() p.communicate(value); 

Again, note the 'b'. Now if your value is a string you get from an API that only returns strings no matter what, then you need to encode it.

p.communicate(value.encode('latin-1'); 

Latin-1, because unlike ASCII it supports all 256 bytes. But that said, having binary data in unicode is asking for trouble. It's better if you can make it binary from the start.



回答2:

You can convert it to bytes with encode method:

>>> "insert into egg values ('egg');".encode('ascii')    # ascii is just an example b"insert into egg values ('egg');" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!