gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:30:09 24 4
gpt4 key购买 nike

当我尝试使用 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'))
  • 将管道包装到一个缓冲文本接口(interface)中,该接口(interface)将进行编码:
  • 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com