当我尝试使用 python 3.2.2 执行此代码时遇到错误
working_file = subprocess.Popen(["/pyRoot/iAmAProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
working_file.stdin.write('message')
我知道 python 3 改变了它处理字符串的方式,但我不明白如何格式化“消息”。有谁知道我将如何将此代码更改为有效?
非常感谢
乔恩
更新:继承人我得到的错误信息
Traceback (most recent call last):
File "/pyRoot/goRender.py", line 18, in <module>
working_file.stdin.write('3')
TypeError: 'str' does not support the buffer interface
最佳答案
如果您有一个要写入管道(而不是字节对象)的字符串变量,您有两种选择:
working_file.stdin.write('message'.encode('utf-8'))
stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8')
stdin_wrapper.write('message')
(请注意,I/O 现在已缓冲,因此您可能需要调用 stdin_wrapper.flush()。)
关于string - python 3.x 中 stdin.write() 的格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486947/