cdkrr
2022-02-23 13:07
采纳率: 100%
浏览 54
已结题

为什么sys.stdout.write写入到标准流之后使用sys.stdin.read无法读取?

问题遇到的现象和发生背景

我调用方法send_message写入标准输出之后,read_thread_func 并不能读取到标准输出中的信息。

问题相关代码,请勿粘贴截图
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# A simple native messaging host. Shows a tkinter dialog with incoming messages
# that also allows to send message back to the webapp.

import struct
import sys
import threading
import queue

try:
  import tkinter
  import tkMessageBox
except ImportError:
  Tkinter = None

# On Windows, the default I/O mode is O_TEXT. Set this to O_BINARY
# to avoid unwanted modifications of the input/output streams.
if sys.platform == "win32":
  import os, msvcrt
  msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
  msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

# Helper function that sends a message to the webapp.
def send_message(message):
   # Write message size.
  sys.stdout.write(struct.pack("I", len(message)).decode('utf-8'))
  # Write the message itself.
  sys.stdout.write(message)
  sys.stdout.flush()

# Thread that reads messages from the webapp.
def read_thread_func(queue):
  message_number = 0
  print('-------------------')
  while 1:
    # Read the message length (first 4 bytes).    
    text_length_bytes = sys.stdin.read(4).encode()  

    if len(text_length_bytes) == 0:
      if queue:
        queue.put(None)
      #os.system("pause")
      sys.exit(0)

    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]

    # Read the text (JSON object) of the message.
    text = sys.stdin.read(10)

    if queue:
      queue.put(text)
    else:
      # In headless mode just send an echo message back.
      send_message('{"echo": %s}' % text)

if tkinter:
  class NativeMessagingWindow(tkinter.Frame):
    def __init__(self, queue):
      self.queue = queue

      tkinter.Frame.__init__(self)
      self.pack()

      self.text = tkinter.Text(self)
      self.text.grid(row=0, column=0, padx=10, pady=10, columnspan=2)
      self.text.config(state=tkinter.DISABLED, height=10, width=40)

      self.messageContent = tkinter.StringVar()
      self.sendEntry = tkinter.Entry(self, textvariable=self.messageContent)
      self.sendEntry.grid(row=1, column=0, padx=10, pady=10)

      self.sendButton = tkinter.Button(self, text="Send", command=self.onSend)
      self.sendButton.grid(row=1, column=1, padx=10, pady=10)

      self.after(100, self.processMessages)

    def processMessages(self):
      while not self.queue.empty():
        message = self.queue.get_nowait()
        if message == None:
          self.quit()
          return
        self.log("Received %s" % message)

      self.after(100, self.processMessages)

    def onSend(self):
      text = '{"text": "' + self.messageContent.get() + '"}'
      self.log('~~~~~Sending %s' % text)
      try:
        send_message(text)
      except IOError:
        tkMessageBox.showinfo('Native Messaging Example',
                              'Failed to send message.')
        sys.exit(1)

    def log(self, message):
      self.text.config(state=tkinter.NORMAL)
      self.text.insert(tkinter.END, message + "\n")
      self.text.config(state=tkinter.DISABLED)


def Main():
  if not tkinter:
    send_message('"tkinter python module was not found. Running in headless ' +
                 'mode. Please consider installing Tkinter."')
    read_thread_func(None)
    sys.exit(0)

  Queue = queue.Queue()

  main_window = NativeMessagingWindow(Queue)
  main_window.master.title('Native Messaging Example')

  thread = threading.Thread(target=read_thread_func, args=(Queue,))
  thread.daemon = True
  thread.start()


  main_window.mainloop()
  #os.system("pause")
  sys.exit(0)


if __name__ == '__main__':
  Main()

运行结果及报错内容

运行结果就是发送信息以后,read_thread_func并不能读取标准输出中的信息

我的解答思路和尝试过的方法

我尝试在send_message中写入标准输出时加入换行回车,并没用

我想要达到的结果

我希望read_thread_func可以接收到信息,非常感谢。

2条回答 默认 最新

相关推荐 更多相似问题