3

I need to create a service in Python so I can send a text from a Google Chrome extension, then this service read it from the STDIO, then do an small processing and then send it back to the chrome extension via STDOUT.

I have the following code I got from the [sample host] you have on the following URL:

https://developer.chrome.com/extensions/nativeMessaging#examples

My problem is that this code has a window (user interface) that I want to remove.

I want this code has a main loop, so it is all the time pending to whatever request from the google chrome extension.

#!/usr/bin/env python

import struct
import sys
import threading
import Queue
try:
    import Tkinter
    import tkMessageBox
except ImportError:
    Tkinter = None

if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

def send_message(message):
  sys.stdout.write(struct.pack('I', len(message)))
  sys.stdout.write(message)
  sys.stdout.flush()

def read_thread_func(queue):
    while 1:
        text_length_bytes = sys.stdin.read(4)
        if len(text_length_bytes) == 0:
            if queue:
                queue.put(None)
            sys.exit(0)
        text_length = struct.unpack('i', text_length_bytes)[0]
        text = sys.stdin.read(text_length).decode('utf-8')
        if queue:
            queue.put(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 wasn\'t 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()
  sys.exit(0)

if __name__ == '__main__':
    Main()

Any idea on how to remove the GUI and make the program pending to external requests?

Angel
  • 611
  • 2
  • 10
  • 18

1 Answers1

1

If I'm interpreting your question right, you want the program to keep on running but not show a console window. To do this, just change the extension of your file from .py to .pyw

Adi219
  • 4,712
  • 2
  • 20
  • 43
  • but I need a code that doesn't have any window. I wanna get rid of it. What I want to happen is that when a text be received from the STDIN, the text gets transformed for example: "*** ***" and then this transformation be delivered back on the STDOUT. And I also need the code be listening all the time for further requests. I mean, I want something more than just change the extension. Actually, the code I'm running doesn't have any extension. It runs well with the GUI window, though. – Angel Aug 12 '17 at 19:06
  • @Aditya Chaurasia that only works in windows, and it won't supress the tk gui. – t.m.adam Aug 12 '17 at 21:00
  • @t.m.adam you are right, are you looking for the same thing now?, maybe we can investigate together via the stackoverflow chat. I have been activeley looking for this but nothing really helpful so far – Angel Aug 12 '17 at 21:59
  • @Angel Fisrtly you have to remove the tk parts from your code. Then search for daemon in python. This might be helpful: [how-do-you-create-a-daemon-in-python](https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python) – t.m.adam Aug 12 '17 at 22:09