Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Diff. between Py 2.7 and 3
#1
Hi,

The following code gets the wifi quality type on a raspberry pi and works with 2.7 but not with 3.0.

The error generated is

Quote:Traceback (most recent call last):
File "test.py", line 9, in <module>
if line.startswith("Quality"):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str

The startswith method used is correct based on the manual
str.startswith(str, beg = 0,end = len(string));
so, not sure where the error is.

I appreciate some insights.
TIA

from subprocess import check_output

'''get wifi connection printout'''
scanoutput = check_output(["iwlist", "wlan0", "scan"])

'''separate bytes'''
for line in scanoutput.split():
  '''filter the quality line out'''
  if line.startswith("Quality"):
     '''remove text from it'''
     level = line.split('=')[1]
     '''get the divisor'''
     lev0 = float(level.split('/')[0])
     '''get the divident'''
     lev1 = float(level.split('/')[1])
     '''devide and multiply by 100 to get the %'''
     cal = int(lev0 / lev1) * 100
     print("{}%".format(str(cal)))
Reply
#2
Received data a for check_output() will be bytes,so need to decode() to string.
Example:
>>> s = b'Quality is good'
>>> if s.startswith('Quality'):
...     print('True')
...     
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: startswith first arg must be bytes or a tuple of bytes, not str

>>> # Fix
>>> s = s.decode() #same as s.decode('utf-8')
>>> if s.startswith('Quality'):
...     print('True')
...     
True
Reply
#3
Fixed it, Thank you!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to diff pandas rows and modify column value Mekala 1 1,721 Sep-18-2020, 12:38 PM
Last Post: Mekala
  Diff. between Py 2.7 and 3 ebolisa 1 2,128 Nov-01-2018, 06:45 PM
Last Post: wavic
  Diff Check - Print from dcmp.diff_files ipuente 0 2,615 Jun-22-2018, 09:44 PM
Last Post: ipuente
  Diff between 1 file to serveral files tcpip 3 3,853 Aug-21-2017, 08:54 AM
Last Post: tcpip

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020