Python 3.x中如何为stdin.write()格式化字符串

10

我遇到了一个问题,当我尝试在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改变了它处理字符串的方式,但我不知道如何格式化“message”。 有人知道我该如何更改此代码才能使其有效吗?感谢大家。
更新:这是我收到的错误信息。
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

你忘记了错误信息。 - Lennart Regebro
2个回答

9

您的错误信息是“TypeError:'str' does not support the buffer interface”吗?这个错误信息几乎可以告诉您发生了什么问题。您不能将字符串对象写入到该sdtin中。那你应该写什么呢?好吧,任何支持缓冲区接口的内容都可以。通常这是字节对象。

比如:

working_file.stdin.write(b'message')

9

如果您有一个字符串变量想要写入管道(而不是字节对象),您有两个选择:

  1. 在写入管道之前先编码该字符串:

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()。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接