0

I'm running python 3.5. After capturing the output from the terminal it appears slightly different in my Python IDE. It's got additional characters I don't need i.e. '\n' or "b''". I tried to use split() and replace() but nothing is working. What am I doing wrong?

def runIndexTest(zone):

    print('Turning OFF flit on ' + zone)
    #setIndexStatus(zone, 'stop')

    cmd1 = 'psql -h ' + zone + ' -U filmlight -t -c ' + '"' + """SELECT datname FROM pg_database WHERE datistemplate = false AND datname LIKE """ + "'fsdb%'" + ';"'
    #print(cmd1)

    out = subprocess.run(cmd1, shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    print(out.stdout)

    db_list = str(out.stdout).split(' ')
    for db in db_list:
        db = db.replace("\n", '')
        if db == "b'":
            db_list.remove(db)
            continue

    print('Length of db_list:', len(db_list))
    print(db_list)

Output:

b' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'
Length of db_list: 5
['fsdb\\n', 'fsdb1\\n', 'fsdb_fetish_images$v1\\n', 'fsdb_fetish_images\\n', "fsdb_fetish_images$v2\\n\\n'"]

Desired output:

['fsdb', 'fsdb1', 'fsdb_fetish_images$v1', 'fsdb_fetish_images', 'fsdb_fetish_images$v2']
michal-ko
  • 397
  • 4
  • 12
  • Related: [How do I get rid of the b-prefix in a string in python?](https://stackoverflow.com/questions/41918836/how-do-i-get-rid-of-the-b-prefix-in-a-string-in-python), – wwii Jul 16 '19 at 16:46
  • I think you can use str(your_string_here) function to convert it. But if you use decode("utf-8") it shouldn't appear anyway – michal-ko Jul 17 '19 at 08:43

3 Answers3

1

You can use list comprehension:

db_list = str(out.stdout).split(' ')
db_list = [x.replace("\\n", '') for x in db_list if x!= "b'" ]
AAA
  • 3,520
  • 1
  • 15
  • 31
1

You need to decode the string:

print(out.stdout.decode("utf-8"))
Moira Jones
  • 369
  • 1
  • 7
1

The b'...' is a bytes literal. To make it a str decode it. The '\n''s are newline characters which are white space use str.split() with the default argument (whitespace).

In [9]: s
Out[9]: b' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'

In [10]: s.decode('utf-8')
Out[10]: ' fsdb\n fsdb1\n fsdb_fetish_images$v1\n fsdb_fetish_images\n fsdb_fetish_images$v2\n\n'

In [11]: s.decode('utf-8').split()
Out[11]: 
['fsdb',
 'fsdb1',
 'fsdb_fetish_images$v1',
 'fsdb_fetish_images',
 'fsdb_fetish_images$v2']
wwii
  • 23,232
  • 7
  • 37
  • 77