ZPL Reading printer status

Hi, I am trying to get my script working where I am trying to query printer status using ZPL. The response consists of multiple lines. I successfully read all the data i need and when there there is no data to be read, the code just hangs probably waiting for more data to come. Now I dont know how to tell the code to not to wait anymore. Below is my code:

  client_socket = Socket(self.host, self.port)
  output_stream = DataOutputStream(client_socket.getOutputStream())
  output_stream.writeBytes(command)
  input_stream = BufferedReader(InputStreamReader(client_socket.getInputStream()))

  buf = ""
  while True:
      line = input_stream.readLine()
      if line:
          buf += line
      else:
          break
   
  input_stream.close()
  client_socket.close()

print buf

In my case, printer responds to ~HS with three lines. The loop runs three time and gets stuck on the fourth run on line = input_stream.readLine().

Could anyone advise?

Thank you

Count the lines and exit after the third.

A more robust solution would use a separate thread for this, with code that examines each line, extracts the information as it arrives, and places it in appropriate tags for the rest of the system to consume.

I could count to three and then exit the loop but I will be using this for calling other commands that might return more or less than three lines. Is there a way to check if there is a text to read and if not then exit the loop?

I found a example for BufferedReader to do this but It was Java example and I dont know how to use it in Jython.

3.2. Reading Line-by-Line

I copied out only part of my code for this post. I will be calling this in separate thread.

You can use a timeout, but such techniques are unreliable for network traffic.

Sounds like you need a long-lived thread and socket. This is tricky. Some discussions for you:

https://forum.inductiveautomation.com/search?q=long-lived%20thread%20order%3Alatest