当前位置: 首页>>代码示例>>Python>>正文


Python MPDClient.list方法代码示例

本文整理汇总了Python中mpd.MPDClient.list方法的典型用法代码示例。如果您正苦于以下问题:Python MPDClient.list方法的具体用法?Python MPDClient.list怎么用?Python MPDClient.list使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mpd.MPDClient的用法示例。


在下文中一共展示了MPDClient.list方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: albums

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
def albums(request):
    c = MPDClient()
    c.connect("localhost", 6600)
    albums = filter(lambda x: x, c.list("album"))
    c.disconnect()
    return render(request, 'albums.html', {
        'page': 'playlist',
        'albums': albums,
    })
开发者ID:allo-,项目名称:mpdsongvote,代码行数:11,代码来源:views.py

示例2: MusicPlayer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class MusicPlayer(Action):
    """MusicPlayer for Ambrosio"""
    def __init__(self, cfg):
        super(MusicPlayer, self).__init__(cfg)
        self.triggers = ["music", "audio"]
        self.mpd = MPDClient()
        self.mpd.connect("localhost", "6600")

    def _do_update(self, command):
        self.mpd.update()

    def _do_play(self, command):
        return self.mpd.play()

    def _do_add(self, command):
        canco = " ".join(command[1:])
        return self.mpd.addid(canco)

    def _do_queue(self, command):
        return "List: %s" %(self.mpd.playlist())

    def _do_songs(self, command):
        llista = self.mpd.list('file')
        print llista
        if len(llista) > 0:
            return '\n'.join(llista)
        else:
            return 'Llista buida'

    def do(self, command):
        print "Will play music ", " ".join(command)
        print command
        if command[0] == "update":
            self._do_update(command)
        elif command[0] == "songs":
            return self._do_songs(command)
        elif command[0] == "add":
            return self._do_add(command)
        elif command[0] == "play":
            return self._do_play(command)
        elif command[0] == "queue":
            return self._do_queue(command)
        else:
            return "Que?!?!?"


    def is_for_you(self, word):
        if word in self.triggers:
            return True
        return False
开发者ID:carlesm,项目名称:ambrosio,代码行数:52,代码来源:MusicPlayer.py

示例3: generate_by_artist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
def generate_by_artist(spec):
    '''choose HOWMANY random artists, and for each one choose a random song'''
    spec.setdefault('howmany', 1)
    log.info('generating')
    conf = get_conf()
    c = MPDClient(use_unicode=True)
    c.connect(conf['MPD_HOST'], conf['MPD_PORT'])

    artists = c.list('artist')
    log.debug("got %d artists", len(artists))
    if not artists:
        raise ValueError("no artists in your mpd database")
    for _ in range(spec['howmany']):
        artist = random.choice(artists)
        yield random.choice(c.find('artist', artist))['file']
开发者ID:boyska,项目名称:larigira,代码行数:17,代码来源:audiogen_mpdrandom.py

示例4: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class lcdmpd:
    """
    """
    # available configuration parameters
    cache_timeout = 2
    color = BLUE
    format_line1 = '{artist}-{title}'
    format_line2 = '{elapsed}/{duration}'
    host = 'localhost'
    max_width = 16
    port = '6600'

    def __init__(self):
        self.text = ['', '']
        try:
            self.c = MPDClient()
            self.c.connect(host=self.host, port=self.port)
        except ConnectionError:
            self.text[0] = "Can't connect"
            pass

    def disconnect(self):
        self.c.disconnect()

    def song_list(self, artist=''):
        song_l = self.c.list('Title', 'Artist', artist)

        return ScrollType(sorted(song_l), CYAN)

    def play_song(self, song=''):
        print self.c._fetch_command_list

    def artist_list(self):
        self.play_song()
        artist_l = self.c.list('Artist')
        return ScrollType(sorted(artist_l), BLUE)


    def current_track_dyn(self):
        track = self.current_track()
        #color = self.current_track()

        d = DynamicType(self.current_track_text,track['color'])
        return d


    def current_track(self, colors=(GREEN, RED)):

        self.colors = {'color_good': colors[0],
                       'color_bad': colors[1]}
        line_1 = ""
        line_2 = ""

        status = self.c.status()
        #print status
        song = int(status.get("song", 0))


        if (status["state"] == "pause") or (status["state"] == "stop"):
            line_1 = ""
        else:

            try:
                song_time = self.c.playlistinfo()[song]
                time = status['time'].split(':')
                #print
                #print song_time
                #print
                song_time["elapsed"] = convert_sec_to_min(time[0])
                song_time["duration"] = convert_sec_to_min(time[1])
            except IndexError:
                song_time = {}

            format_args = song_time
            line_1 = self.format_line1
            line_2 = self.format_line2
            for k, v in format_args.items():
                line_1 = line_1.replace("{" + k + "}", str(v))
                line_2 = line_2.replace("{" + k + "}", str(v))

            for sub in re.findall(r"{\S+?}", line_1):
                line_1 = line_1.replace(sub, "")


        #if len(line_1) > self.max_width:
        #    line_1 = line_1[:self.max_width-2] + ".."
        #if len(line_2) > self.max_width:
        #    line_2 = line_2[:self.max_width-2] + ".."

        if (self.text[0] != line_1) or (self.text[1] != line_2):
            transformed = True
            self.text[0] = line_1
            self.text[1] = line_2
        else:
            transformed = False

        response = {
            'full_text': self.text,
            'transformed': transformed,
            'color': None
#.........这里部分代码省略.........
开发者ID:UmBsublime,项目名称:pybox,代码行数:103,代码来源:lcdmpd.py

示例5: print

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
for opt, arg in optlist:
    if opt == "-h":
        host = arg
    elif opt == "-p":
        port = arg
    elif opt == "-d":
        dbname = arg
    else:
        print("Usage: python %s [-h <mpdhost>] [-p <mpdport>]" % sys.argv[0])
        sys.exit(1)

# Retrieve artists from MPD
client = MPDClient()
client.connect(host, port)
artists = sorted(client.list("artist"))
client.close()
client.disconnect()

# Create SQLite connection
db = connect(dbname)
db.execute("DROP TABLE IF EXISTS artists")
db.execute("DROP TABLE IF EXISTS similarities")
db.commit()

db.execute("CREATE TABLE artists(artist varchar(1024) primary key asc)")
db.commit()

db.execute(
    "CREATE TABLE similarities("
    + "artist varchar(1024), "
开发者ID:BlackLight,项目名称:symartists,代码行数:32,代码来源:mpdartists.py

示例6: MusicPlayer

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class MusicPlayer(Action):
    """MusicPlayer for Alfred"""
    def __init__(self, cfg):
        super(MusicPlayer, self).__init__(cfg)
        self.triggers = ["music","audio"]
        self.mpd = MPDClient()
        self.mpd.connect("localhost", "6600")
        self.mpd.consume(0)

    def _do_update(self, command):
        self.mpd.update()

    def _do_list(self, command):
        llista = self.mpd.list('file')
        print llista
        if len(llista) > 0:
            return "\n".join(llista)
        else:
            return "Empty List SIR"

    def _do_add(self, command):
        song = " ".join(command[1:])
        self.mpd.add(song)
        return "Song %s Added SIR" % (song)

    def _do_queue(self,command):
        return "list: %s" % (self.mpd.playlist())

    def _do_clear(self, command):
        self.mpd.clear()
        return "Clear Done SIR"

    def _do_next(self, command):
        self.mpd.next()
        return "Next Song Done SIR"

    def _do_previous(self, command):
        self.mpd.previous()
        return "Previous Song Done SIR"

    def _do_pause(self, command):
        self.mpd.pause()
        return "Music Paused SIR"

    def _do_shuffle(self, command):
        self.mpd.shuffle()
        return "Music shuffled SIR"

    def _do_repeat(self, command):
        try:
            if command[1] == "on":
                self.mpd.repeat(1)
                return "Repeat Set On SIR"
            elif command[1] == "off":
                self.mpd.repeat(0)
                return "Repeat Set Off SIR"
            else:
                return "Error SIR"
        except:
            return "Error SIR"

    def _do_play(self, command):
        try:
            songpos = command[1]
            self.mpd.play(int(songpos))
            return "Playing %s Song Done SIR" % (songpos)
        except:
            self.mpd.play()
            return "Music Playing SIR"

    def _do_stop(self, command):
        self.mpd.stop()
        return "Music Stoped SIR"

    def do(self, command):
        print "Will", " ".join(command), "music"
        print command
        if command[0] == "update":
            self._do_update(command)
        elif command[0] == "list":
            return self._do_list(command)
        elif command[0] == "add":
            return self._do_add(command)
        elif command[0] == "queue":
            return self._do_queue(command)
        elif command[0] == "play":
            return self._do_play(command)
        elif command[0] == "stop":
            return self._do_stop(command)
        elif command[0] == "clear":
            return self._do_clear(command)
        elif command[0] == "next":
            return self._do_next(command)
        elif command[0] == "previous":
            return self._do_previous(command)
        elif command[0] == "pause":
            return self._do_pause(command)
        elif command[0] == "repeat":
            return self._do_repeat(command)
        elif command[0] == "shuffle":
#.........这里部分代码省略.........
开发者ID:Costar93,项目名称:Alfred,代码行数:103,代码来源:MusicPlayer.py

示例7: Player

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]

#.........这里部分代码省略.........
            print('Maximum attempts exceeded')


    def MPDclearPlayList(self):
        for i in xrange(5):
            try:
                self.client.clear()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDplay(self):
        for i in xrange(5):
            try:
                self.client.play()
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDscanArtists(self):
        """ Scans music database for unique artists names,
            makes the DB of their names first letters """
        print('Building structure...')
        for i in xrange(5):
            try:
                self.artists = sorted(self.client.list('artist'))
                self.artistsFirstLettersU = []
                for i, artist in enumerate(self.artists):
                    if len(artist)>0:
                        cU = artist.decode('utf-8')[0]
                        if cU not in self.artistsFirstLettersU:
                            self.artistsFirstLettersU.append(cU)
                self.maxLetterNumber = len(self.artistsFirstLettersU)
                print('Done!')
                break
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDscanArtistsAlbums(self, myartist):
        """ Scans music database for artist's albums
            returns albums names """
        for i in xrange(5):
            try:
                myalbums = sorted(self.client.list('album',
                                                   'artist', myartist))
                return myalbums
            except:
                self.connected_to_mpd = False
                self.MPDserverconnect()
        else:
            print('Maximum attempts exceeded')


    def MPDpause(self):
开发者ID:OSliusarenko,项目名称:yaih,代码行数:70,代码来源:player2.py

示例8: delete_event

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]

#.........这里部分代码省略.........
            if piconfig.mpd == True:
                self.music = True
                self.current = True
                self.artist = False
                self.album = False
                self.tracks = False
                self.options = False
                self.hasFormer = False
                self.sudo.set_text("music")
                self.sudo.show()
                query = ""
                self.entry.set_text("")
                self.mclient = MPDClient()
                self.connected = False
                self.delcur = False
                if self.connected == False:
                    try:
                        self.mclient.connect(piconfig.mpdcon['host'], piconfig.mpdcon['port'])
                        self.connected = True
                    except:
                        self.connected = False
                        print "failed to connect"
                        return
                self.getMusic()
                return
        #need this here for posterity
        if self.calc == True or self.isHttp == True or self.websearch == True:
            self.scrollbox.hide()
            return
        match = []
        for i in self.path.split(":"):
            i = i.strip()
            try:
                for filename in os.listdir(i):
                    if filename.startswith(query):
                        if os.path.isfile(i + "/" + filename):
                            filename = filename.strip()
                            match.append(filename)
            except OSError:
                print i + "not found"
        match.sort()
                
        #add history to beginning
        if os.path.exists(self.hist):
            file = open(self.hist)
            for line in file.readlines():
                if line.startswith(query):
                    line = line.strip()
                    if line in match:
                        match.remove(line)
                    match.insert(0, line)
                    
        #add preferred programs to beginning (before history)
        if len(piconfig.preferredApps) > 0:
            for app in piconfig.preferredApps:
                if app.startswith(query):
                    if app in match:
                        match.remove(app)
                    match.insert(0, app)

        if len(match)!=0:
            for k in match:
                self.tree.append([k])
            self.prevArr = []
            self.scrollbox.show()
            self.rbox.scroll_to_cell('0', column=None)
开发者ID:vincekd,项目名称:Pilaunch,代码行数:70,代码来源:pilaunch.py

示例9: MPDClient

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
from socket import error as SocketError
from sys import exit


## SETTINGS
##
HOST = 'localhost'
PORT = '6600'
PASSWORD = False
###


client = MPDClient()

try:
    client.connect(host=HOST, port=PORT)
except SocketError:
    exit(1)

if PASSWORD:
    try:
        client.password(PASSWORD)
    except CommandError:
        exit(1)

client.add(choice(client.list('file')))
client.disconnect()

# VIM MODLINE
# vim: ai ts=4 sw=4 sts=4 expandtab
开发者ID:HikaruLim,项目名称:python-mpd2,代码行数:32,代码来源:randomqueue.py

示例10: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class player:
	def __init__(self,server):
		# Parameters
		if os.path.expanduser("~")<>"/root":
			self.config_dir = os.path.expanduser("~")+"/.dukebox/"
		else:
			# Nasty hack for running dukeboxd as root
			self.config_dir = "/home/pi/.dukebox/"
		self.server = server
		self.create_time = time.time()
		self.read_config()

		# Connect to MPD
		self.c = MPDClient()              
		self.c.timeout = 10
		self.c.idletimeout = None
		self.connect()
		
		status = self.c.status()
		if status.get("state")!="stop":
			temp = self.c.currentsong()
			self.genre = "All"
			self.last_genre = ""
			if status.get("random")=="1":
				print "+ Appear to be in track mode"
				self.mode = "track"
			else:
				self.mode = "album"
			# TODO - radio mode
			self.last_mode = ""
			self.last_song = temp.get("id")
			self.last_pos  = status.get("elapsed")
		else:		
			self.genre = "All"
			self.last_genre = ""
			self.mode = "album"
			self.last_mode = ""

		self.i=dict()
		self.n=dict()
		self.read_album_list()
		# List that changes depending on the genre selected
		self.some_albums = list(self.albums)
		# List of all albums that remains static for text search
		self.sort_albums = list(self.albums)
		self.album_art_stub = ""
		self.track_lengths = []
		
		seed()
		shuffle(self.albums)
		self.set_radio_stations()
		print "+ Music lists read: "+str(len(self.albums))+" local albums and "+str(len(self.radio_stations))+" radio stations."
		
		self.speak_lock = False


	def __del__(self):
		# Close the socket
		if self.connected:
			self.disconnect()
		
		
	def connect(self):
		print "+ Connecting to <"+self.server+">"
		try:
			self.c.connect(self.server, 6600)
			#print "+              ...connected"
			self.connected = True
			self.connected = True
			return True
		except:
			print "# Could not connect"
			self.connected = False
			return False
	
	
	def disconnect(self):
		print "+ Disconnecting from <"+self.server+">"
		self.c.close()
		self.c.disconnect()
			
		
	def read_config(self):
		# Defaults
		width = 1024
		height = 550
		self.fullscreen = False
		self.graphics = "simple"
		self.speak_option = "none"
		self.try_reading_battery = True
		self.screensaver_time = 30000
		
		# Read the Dukebox config file
		config_file = self.config_dir+"dukebox.conf"
		if os.path.isfile(config_file):
			for line in open(config_file):
				if line[0]!="#":
					try:
						if "width" in line:
							width = int(line.split("=")[-1].strip())
#.........这里部分代码省略.........
开发者ID:Bisxuit,项目名称:dukebox,代码行数:103,代码来源:dukebox_player.py

示例11: library

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class MPCWebSimple:
	"""Simple MPD Web Client

	GOALS
	CherryPyMPC 0.2 will be able to:
		- display playlist, file tree, and artist/album tree in different tabs
			(without reloading the whole page)
		- update the library (auto refresh when done)
		- seek in a song, graphically
		- be styled much better than 0.1 :-)

	REQS
		- python 2.x
		- python-mpd
		- cherrypy
		
	RUN
		- ./cherrypympc.py"""

# init
	def __init__(self, host, port, passw):
		self.__app__ = "CherryPyMPC 0.2 (static/iframe)"
		self.c = MPDClient()
		self.c.connect(host, port)
		if passw:
			self.c.password(passw)

# actions
	def play(self):
		self.c.play()
		raise cherrypy.HTTPRedirect("/")

	def pause(self):
		self.c.pause()
		raise cherrypy.HTTPRedirect("/")

	def stop(self):
		self.c.stop()
		raise cherrypy.HTTPRedirect("/")

	def prev(self):
		self.c.previous()
		raise cherrypy.HTTPRedirect("/")

	def next(self):
		self.c.next()
		raise cherrypy.HTTPRedirect("/")

	def playno(self, pos):
		if pos:
			self.c.playid(int(pos))
		raise cherrypy.HTTPRedirect("/")

	def addsong(self, song):
		self.c.add(song[1:-1])
		raise cherrypy.HTTPRedirect("/")

	def seek(self, pos, secs):
		self.c.seek(pos, secs)
		cherrypy.response.headers['content-type']='text/plain'
		return "OK"

	def update(self):
		self.c.update()
		cherrypy.response.headers['content-type']='text/plain'
		return "OK"

	def findadd(self, field, query, field2=None, query2=None):
		if field2 and query2:
			self.c.findadd(field, query, field2, query2)
		else:
			self.c.findadd(field, query)
		raise cherrypy.HTTPRedirect("/")

# subframe html
	def playlist(self):
		current_track = self.c.currentsong()['pos']
		plinfo = self.c.playlistinfo()
		pltable = "<table class='playlist'><tr class='header'><th>&nbsp;</th><th>Artist</th><th>Track</th><th>Lengtr</th></tr>"
		for item in plinfo:
			trclass = ""
			if item["pos"] == current_track:
				trclass = " class='currentsong'"
			pltable += "<tr{tr_class} onclick='top.location.href=\"/playno?pos={plpos}\"'><td><img src='/img/musicfile.png' /></td><td>{artist}</td><td>{title}</td><td class='tracklen'>{length}</td></tr>".format( \
					plpos=item["pos"],
					artist=item.get("artist", "&nbsp;"),
					title=item.get("title", item["file"].split("/")[-1]),
					length=SecToTimeString(item["time"]),
					tr_class=trclass)
		pltable += "</table>"
		return self.surround_head_tags_basic(pltable)

	def filetree(self):
		treelist = TreeList(self.c.list('file'))
		def make_ul(tlist, path=[], level=0):
			r = "<ul" + ("" if (level is not 0) else " class='tree'") + ">"
			if len(tlist) > 1:
				flist = sorted(tlist[1:])
				for filename in flist:
					liclass = "" if (filename is not flist[-1] or len(tlist[0].keys()) > 1) else " class='last'"
#.........这里部分代码省略.........
开发者ID:casmarrav,项目名称:cherrypympc,代码行数:103,代码来源:cherrypympc.py

示例12: PrettyPrintTreeList

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
	from mpd import MPDClient

	def PrettyPrintTreeList(tree_list, level=0):
		if len(tree_list) > 1:
			for filename in tree_list[1:]:
				print (level * "    ") + "*" + filename
		for subdir in tree_list[0].keys():
			print level * "    " + subdir + ">"
			PrettyPrintTreeList(tree_list[0][subdir], level+1)

	c = MPDClient()
	c.connect(host="localhost", port="6600")

	print "printing current playlist, artist - title (# from album)"
	plist = c.playlistinfo()
	for item in plist:
		print "{pos}: {artist} - {title} (#{track} from {album})".format(pos = item["pos"],
																	artist = item["artist"],
																	title = item["title"],
																	track = item["track"],
																	album = item["album"])

	print "grabbing entire MPD dir struct"
	flist = c.list('file')
	tlist = TreeList(flist)

	print "printing entire MPD dir struct"
	PrettyPrintTreeList(tlist)

# vim: ts=4 sw=4 noet
开发者ID:casmarrav,项目名称:cherrypympc,代码行数:32,代码来源:mpclib.py

示例13: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
class MPDApi:
    def __init__(self, host='localhost', port='6600'):
        self.__api = MPDClient()
        self.__api.connect(host, port)

        self.__song_db = {}
        # If there are songs in the MPD queue, rebuild their info.
        for file_ in self.__api.playlist():
            file_ = file_[6:]
            song = self.playlist_find(file_)
            song_dict = self.translate_song(song)
            self.__song_db[file_] = song_dict

    @property
    def queue(self):
        queue = []
        if self.__api.currentsong():
            current_pos = int(self.__api.currentsong()['pos'])
            queue = self.__api.playlist()[current_pos:]
        return map(lambda x: x[6:], queue)

    @property
    def current_song(self):
        track = self.__api.currentsong()
        if track:
            return self.song_db.get(track['file'])
        return None

    @property
    def song_db(self):
        return self.__song_db.copy()

    def __state(self):
        return self.__api.status()['state']

    def request_song_from_api(self, search):
        search_result = self.__api.search('title', search)
        result = None
        if search_result:
            result = self.translate_song(search_result[0])
            self.__song_db[result['SongID']] = result
        return result

    def queue_song(self, file_):
        if self.__state == 'stop' and len(self.queue) == 0:
            self.__api.playid(self.playlist_find(file_)['id'])
        else:
            self.__api.add(file_)

    def auto_play(self):
        if self.__state() == 'stop' and not len(self.queue) == 0:
            while True:
                random_song = 'file: %s' % choice(self.__api.list('file'))
                if random_song not in self.__api.playlist():
                    self.queue_song(random_song)
                    break

    def remove_queue(self, file_):
        song = self.playlist_find(file_)
        if song:
            self.__api.delete(song['pos'])
            return True
        return False

    def translate_song(self, song_dict):
        result = dict(SongID=song_dict['file'])
        for key, tag in dict(SongName='title', ArtistName='artist',
                AlbumName='album').items():
            try:
                result[key] = util.asciify(song_dict[tag])
            except:
                # This song does not have that key.  Probably a .wav
                pass
        return result

    def playlist_find(self, filename):
        song = self.__api.playlistfind('file', filename)
        if song:
            return song[0]
        return None

    ###### API CALLS #######
    def api_pause(self):
        """
        Pauses the current song
        Does nothing if no song is playing
        """
        self.__api.pause()

    def api_play(self):
        """
        Plays the current song
        If the current song is paused it resumes the song
        If no songs are in the queue, it does nothing
        """
        if self.__state() == 'pause':
            self.__api.play()
        else:
            self.auto_play()

#.........这里部分代码省略.........
开发者ID:Qalthos,项目名称:groovebot,代码行数:103,代码来源:MPDApi.py

示例14: print

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import list [as 别名]
    elif opt == "-H":
        config["mpdhost"] = arg
    elif opt == "-P":
        config["mpdport"] = arg
    elif opt == "-h":
        print(
            "Usage: python %s [-h] [-a <artist>] [-g <genre>] "
            + "[-H <mpdhost> (default: localhost)] [-P <mpdport> (default: 6600)]" % argv[0]
        )
        exit(0)

client = MPDClient()
client.connect(config["mpdhost"], config["mpdport"])

if config["genre"]:
    albums = client.list("album", "genre", config["genre"])
elif config["artist"]:
    albums = client.list("album", "artist", config["artist"])
else:
    albums = client.list("album")

shuffle(albums)
randAlbum = albums[0]

artists = client.list("artist", "album", randAlbum)
if len(artists) > 1:
    artist = artists[randint(0, len(artists) - 1)]
else:
    artist = artists[0]

files = find({"Artist": artist, "Album": randAlbum})
开发者ID:kdbdallas,项目名称:mpdrand,代码行数:33,代码来源:mpdrand.py


注:本文中的mpd.MPDClient.list方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。