在python 3.x中格式化stdin.write()的字符串

jon*_*opf 10 string stdin python-3.x

当我尝试使用python 3.2.2执行此代码时,我遇到了一个问题

working_file = subprocess.Popen(["/pyRoot/iAmAProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

working_file.stdin.write('message')
Run Code Online (Sandbox Code Playgroud)

我知道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
Run Code Online (Sandbox Code Playgroud)

Sep*_*rvi 8

我同意之前的回答(除了"错误信息告诉你确切的错误"部分),但我想完成它.如果你有一个你想要写入管道的字符串(而不是字节对象),你有两个选择:

1)在将每个字符串写入管道之前先对其进行编码:

working_file.stdin.write('message'.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

2)将管道包装到一个缓冲的文本界面中,该界面将进行编码:

stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8')
stdin_wrapper.write('message')
Run Code Online (Sandbox Code Playgroud)

(请注意,I/O现在已缓冲,因此您可能需要调用stdin_wrapper.flush().)


Len*_*bro 6

您的错误消息是“ TypeError:'str'不支持缓冲区接口”吗?该错误消息几乎可以告诉您到底是什么问题。您无需将字符串对象写入该sdtin。那你写什么呢?好吧,任何支持缓冲接口的东西。通常,这是字节对象。

喜欢:

working_file.stdin.write(b'message')
Run Code Online (Sandbox Code Playgroud)