user2550138
user2550138

Reputation:

Printing specific line from subprocess.Popen output

I’m using Shairport-Sync meta reader to pipe airplay data and am currently returning strings using the following python3 code:

#!/usr/bin/python
import subprocess
cmd = "shairport-sync-metadata-reader < /tmp/shairport-sync-metadata"
proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)

while True:
  line = proc.stdout.readline()
  print (line)

#   if line != '':
#      wordKeys = ["Artist", "Title", "Album"]
#     lineNow = line.rstrip()
#       for key in wordKeys:
#         if key in lineNow:
#          print (lineNow)
#    else:
#      break

I’ve had trouble isolating the artist, title, and album strings using the code I found on the web. The error I run into with the last lines up commented refers to the ‘type str doesn’t support the buffer API’.

My proc.stdout.readline() output looks like:

b'Client\'s IP: "fe80::1477:d5d0:763a:a093".\n'
b'"ssnc" "svip": "fe80::25f8:b47e:c427:e431".\n'
b'"ssnc" "snua": "AirPlay/352.17.1".\n'
b'"ssnc" "acre": "2761427076".\n'
b'"ssnc" "daid": "FA4CC8448AD2A90E".\n'
b'"ssnc" "pbeg": "".\n'
b'"ssnc" "pvol": "-11.74,-19.48,-96.30,0.00".\n'
b'"ssnc" "pfls": "".\n'
b'"ssnc" "pcst": "2456171464".\n'
b'Picture received, length 95419 bytes.\n'
b'"ssnc" "pcen": "2456171464".\n'
b'"ssnc" "prgr": "2455930277/2456184560/2468648320".\n'
b'"ssnc" "mdst": "2456186320".\n'
b'Album Name: "Funeral".\n'
b'Artist: "Arcade Fire".\n'
b'Composer: "Arcade Fire/Josh Deu".\n'
b'Genre: "Indie Rock".\n'
b'Title: "Neighborhood #1 (Tunnels)".\n'
b'"ssnc" "mden": "2456186320".\n'
b'"ssnc" "pcst": "2456186320".\n'
b'Picture received, length 95419 bytes.\n'
b'"ssnc" "pcen": "2456186320".\n'
b'"ssnc" "prgr": "2456019183/2456191600/2468737226".\n'
b'"ssnc" "prsm": "".\n'

My question is how can I reduce the print output to the values of the lines which relate to artist, track, and album?

Upvotes: 1

Views: 485

Answers (1)

user3151902
user3151902

Reputation: 3176

These are bytes instead of strings, see for example https://docs.python.org/3/reference/lexical_analysis.html#literals

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.

You can use decode to convert them to a string:

line = proc.stdout.readline().decode()

Upvotes: 2

Related Questions