![]() |
|
Diff. between Py 2.7 and 3 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Diff. between Py 2.7 and 3 (/thread-14749.html) |
Diff. between Py 2.7 and 3 - ebolisa - Dec-15-2018 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): 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)))
RE: Diff. between Py 2.7 and 3 - snippsat - Dec-15-2018 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
RE: Diff. between Py 2.7 and 3 - ebolisa - Dec-15-2018 Fixed it, Thank you!! |