1

I have a few projectors that i control with a python script using telnetlib, which works fine. I can also read the telnet output to get the current settings from them.

The issue i am having is that the telnet output gives me some unwanted characters and i would like to filter those out and show just the actual data.

#CURRENT SCRIPT
import time
import telnetlib
import os


port = 555
ipaddr = ('10.0.0.171',
          '10.0.0.172',
          '10.0.0.173',)
for ip in ipaddr:
    tn = telnetlib.Telnet(ip, port,)
    time.sleep(0.1)
    tn.write(b"*gamma ?\r")
    time.sleep(0.1)
    tn.write(b"*power ?\r")
    time.sleep(0.1)
    print(tn.read_eager(), end = ' ')
    print("on " + ip)
    print("----------------------------------------------------")
    tn.close
os.system("pause")

The output looks like this:

b'ack gamma = 3\r\nack power = 1\r\n' on 10.0.0.171
----------------------------------------------------
b'ack gamma = 3\r\nack power = 1\r\n' on 10.0.0.172
----------------------------------------------------
b'ack gamma = 3\r\nack power = 1\r\n' on 10.0.0.173
----------------------------------------------------
Press any key to continue . . .

which basically returns the ACK command and the data with \r\n at the end

is it possible to filter those out and put a delimiter between? something like:

| gamma = 3 | power = 1 | on 10.0.0.171
----------------------------------------------------
| gamma = 3 | power = 1 | on 10.0.0.172
----------------------------------------------------
| gamma = 3 | power = 1 | on 10.0.0.173
----------------------------------------------------
Press any key to continue . . .

Or if it is simpler to output these replies in a popup message box? or highlight them (different color)?

Working on Windows with Python 3.7.3

Any help would be much appreciated, Thanks

David

2 Answers2

2

You get an instance of the bytes built-in type from the Telnet.read_eager() method and must decode it into a string using the bytes.decode() method. Look at the following fragment.

ip = '10.1.1.30'
bs = b'ack gamma = 3\r\nack power = 1\r\n'
print(type(bs))
s = bs.decode()
print(type(s))
s = s.replace('\r\n', ' | ')
print('| '+ s + 'on ' + ip)

Output:

<class 'bytes'>
<class 'str'>
| ack gamma = 3 | ack power = 1 | on 10.1.1.30
Andrei Odegov
  • 2,925
  • 2
  • 15
  • 21
0

You can decode bytes to unicode string using decode:

In [1]: bs = b'hello world'

In [2]: bs
Out[2]: b'hello world'

In [3]: bs.decode('utf-8')
Out[3]: 'hello world'

And string can be encoded into bytes the same way using encode:

In [4]: s = '123456'

In [5]: s.encode()
Out[5]: b'123456'

Then along with regex to grab your desired information. For example:

import re
s = b'ack gamma = 3\r\nack power = 1\r\n on 10.0.0.171'.decode('utf-8')
ip_addr = re.findall(r'\d+\.\d+\.\d+\.\d+', s)[0] # 10.0.0.171
knh190
  • 2,744
  • 1
  • 16
  • 30