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

标签 string python-3.x stdin

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

    相关文章:

    java - 将 matlab 输入 (stdin) 连接到 java

    python - 在 Python 中插入另一个字符代替空格

    java - 使用 StringTokenizer 和 String.split( ) 的区别?

    python - 无法从 JSON 对象在 Python 中打印字符 '\u2019'

    python - 使用 python requests 库将文件发布到服务器时出现错误请求错误

    python sys.stdin.read() 不需要的拆分

    c - 在C中,是否必须传递字符数组名称才能更改字符串常量的字符?

    c - 删除字符串中括号之间的子字符串

    python - 如何使用相同的键将Python字典替换为QueryDict

    c - C 中的日期格式 dd.mm.yyyy