Python 3 writing to a pipe

余生长醉 提交于 2019-11-29 14:05:55

The print function converts its arguments to a string representation, and outputs this string representation to the given file. The string representation always is of type str for both, Python 2.x and Python 3.x. In Python 3.x, a pipe only accepts bytes or buffer objects, so this won't work. (Even if you pass a bytes object to print, it will be converted to a str.)

A solution is to use the write() method instead (and flushing after writing):

self.gnuProcess.stdin.write(bytes(mystr + "\n", "ascii"))
self.gnuProcess.stdin.flush()

but python2 will complain about

bytes("something", "ascii")

if you use the mutable bytearray it will work in both python2 and python3 unaltered

self.gnuProcess.stdin.write(bytearray(mystr + "\n", "ascii"))
self.gnuProcess.stdin.flush()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!