Why do I get b' at the start of each line and ' at the end of each line?

602 views python
3

I have this python script that uses pxssh. Here's the script:

from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = input('hostname: ')
    username = input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('cat hiera/my.yaml')   # run a command
    s.prompt()             # match the prompt
    for line in s.before.splitlines()[1:]:
       print (line)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

and I cannot understand why the script output looks like this:

b'---'
b'settings_prod: |'
b'"""'
b"Generated by 'django-admin startproject' using Django 2.0.5."
b''
b'For more information on this file, see'
b'https://docs.djangoproject.com/en/2.0/topics/settings/'
b''
b'For the full list of settings and their values, see'
b'https://docs.djangoproject.com/en/2.0/ref/settings/'
b'"""'

What is up with the b' at the start of each line and the ' on the end of each line of output? How do I get rid if it?

answered question

It's binary data right? Is this Python3? try print( str( line, 'utf-8' ) )

That does the trick. Thanks

2 Answers

12

From the docs:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

https://docs.python.org/3.3/reference/lexical_analysis.html#string-literals

posted this
8

It's binary data, it needs to be converted with str().

print( str( line, 'utf-8' ) )

There's a bunch of other string formats, like iso-8859-1, iso-8859-16, etc. But, if in doubt, try utf-8 first.

posted this

Have an answer?

JD

Please login first before posting an answer.