#! /usr/bin/env python3

from configparser import ConfigParser
from datetime import datetime
import subprocess
import readline

import requests
from bs4 import BeautifulSoup


_STREAMS = 'http://music.cbc.ca/streams.aspx'


def get_playlists():
    r = requests.get(_STREAMS)
    r.raise_for_status()
    s = BeautifulSoup(r.text, 'lxml')
    return {li.select_one('a.playStream').text:
            li.select_one('.streamUrl > a[href]')['href']
            for li
            in s.select('ul.streams > li')}


def new_completer(playlist):
    def completer(text, state):
        nonlocal playlist
        options = [playlist for playlist in playlists if text in playlist]
        if state < len(options):
            return options[state]
        else:
            return None
    return completer


def play(playlist_url, tee=False):
    r = requests.get(playlist_url)
    r.raise_for_status()

    # Play first working stream
    p = ConfigParser()
    p.read_string(r.text)
    for key, value in p['playlist'].items():
        if (key.startswith('file') and
            subprocess.call(['ffmpeg',
                             '-nostdin',
                             '-i', 'async:' + value] +
                            # Yes, check by identity
                            ([] if not tee else
                             ['-f', 'mp3',
                              '-c', 'copy',
                              './' + datetime.now().replace(microsecond=0).isoformat() + '.mp3']) +
                             ['-f', 'alsa',
                              'default']) == 0):
            break


if __name__ == '__main__':
    from argparse import ArgumentParser

    ap = ArgumentParser('Play/download CBC Radio playlists')
    ap.add_argument('-t', '--tee', action='store_true')
    args = ap.parse_args()

    playlists = get_playlists()
    print(*sorted(playlists), sep='\n')
    readline.parse_and_bind('tab: complete')
    readline.set_completer(new_completer(playlists))
    playlist_url = playlists[input('Playlist: ')]
    play(playlist_url, tee=args.tee)

@@ -1656,16 +1656,41 @@
 ntParser
+%0A    from sys import exit
 %0A%0A    ap
@@ -1796,24 +1796,67 @@
 tore_true')%0A
+    ap.add_argument('playlist', nargs='?')%0A
     args = a
@@ -1899,24 +1899,59 @@
 playlists()%0A
+%0A    if args.playlist is None:%0A    
     print(*s
@@ -1978,16 +1978,20 @@
 p='%5Cn')%0A
+    
     read
@@ -2023,24 +2023,28 @@
  complete')%0A
+    
     readline
@@ -2084,24 +2084,28 @@
 lists))%0A    
+   
+ 
 playlist_url
@@ -2138,16 +2138,176 @@
 st: ')%5D%0A
+    else:%0A        try:%0A            playlist_url = playlists%5Bargs.playlist%5D%0A        except KeyError:%0A            exit('Not a valid playlist: ' + args.playlist)%0A%0A
     play

Support selecting playlist on command line.