【问题标题】:formatting strings for stdin.write() in python 3.xpython 3.x 中 stdin.write() 的格式化字符串
【发布时间】:2011-12-13 09:35:07
【问题描述】:

我在尝试使用 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

【问题讨论】:

  • 您忘记了错误信息。

标签: string python-3.x stdin


【解决方案1】:

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

  1. 在将字符串写入管道之前先对字符串进行编码:
working_file.stdin.write('message'.encode('utf-8'))
  1. 将管道包装到将进行编码的缓冲文本接口中:
stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8')
stdin_wrapper.write('message')

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

【讨论】:

    【解决方案2】:

    你的错误信息是“TypeError: 'str' does not support the buffer interface”吗?该错误消息几乎可以准确地告诉您出了什么问题。您不会将字符串对象写入该 sdtin。那你写什么呢?好吧,任何支持缓冲区接口的东西。通常这是字节对象。

    喜欢:

    working_file.stdin.write(b'message')
    

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 2011-08-22
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多