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


Python MPDClient.close方法代码示例

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


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

示例1: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
class MPDConnection:
   """ Connects and disconnects to a MPD server """

   def __init__(self, host, port, password=None):
      self.host = host
      self.port = port
      self.password = password

      # Always use Unicode in the MPDClient.
      self.client = MPDClient(use_unicode=True)

   def connect(self):
      """ Connect to the MPD server """

      try:
         log.info('Connecting to the MPD server.')

         self.client.connect(self.host, self.port)
      except IOError as err:
         errno, errstr = err
         raise MPDConnectionError("Could not connect to '%s': %s" % (self.host, errstr))
      except MPDError as e:
         raise MPDConnectionError("Could not connect to '%s': %s" % (self.host, e))

      if self.password:
         log.info('Attempting password command.')

         try:
            self.client.password(self.password)
         except CommandError as e:
            raise MPDConnectionError("Could not connect to '%s': "
                              "password command failed: %s" % (self.host, e))
         except (MPDError, IOError) as e:
            raise MPDConnectionError("Could not connect to '%s': "
                              "password command failed: %s" % (self.host, e))
      
   def disconnect(self):
      """ Disconnect from the MPD server """

      log.info('Disconnecting from the MPD server.')

      try:
         self.client.close()
      except (MPDError, IOError):
         log.debug('Could not close client, disconnecting...')
         # Don't worry, just ignore it, disconnect
         pass
      try:
         self.client.disconnect()
      except (MPDError, IOError):
         log.debug('Could not disconnect, resetting client object.')

         # The client object should not be trusted to be re-used.
         self.client = MPDClient(use_unicode=True)

   def reconnect(self):
      """ Reconnects to the MPD server """

      self.disconnect()
      self.connect()
开发者ID:bozbalci,项目名称:oiseau,代码行数:62,代码来源:mpdclient.py

示例2: wrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
    def wrapper(request):
        client = MPDClient()
        try:
            client.connect(settings.MPD_HOST, settings.MPD_PORT)
            if settings.MPD_PASSWORD:
                client.password(settings.MPD_PASSWORD)
            result = func(client) or {"success": True}
        except (MPDError, IOError) as e:
            result = {
                "success": False,
                "error": _("Error while executing %(command)s: %(error_message)s")
                % {"command": func.__name__, "error_message": e},
            }
        finally:
            try:
                client.close()
                client.disconnect()
            except ConnectionError:
                pass

        # add a success key in the result dict if not already present.
        result.setdefault("success", True)

        data = json.dumps(result)
        return HttpResponse(data, content_type="application/json")
开发者ID:rafikdraoui,项目名称:vortex,代码行数:27,代码来源:views.py

示例3: __init__

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

	def __init__( self, music_root ):
		self._music_root = music_root
		self._con = MPDClient()
		self._con.timeout = 10
		self._con.idletimeout = None
		self._con.connect( 'localhost', 6600 )

	def addToDb( self, song_obj ):
		temp = song_obj.getInfo()['file']
		while self._con.find( 'file', temp) == []:
			try:
				temp = temp.split( '/', 1 )[1]
			except IndexError:
				print( 'ERROR: Could not add.  Please put the song (if it exists) under the mpd root.' )
				break
		if self._con.find( 'file', temp) != []:
			self._con.update( temp )
		
	def listDbDir( self, dir_loc ):
		listings = []
		for listing in self._con.lsinfo( dir_loc ):
			temp = Song.Song( self._music_root + listing['file'] )
			listings.append( temp )
		return listings
	
	def __del__( self ):
		self._con.close()
开发者ID:ayypot,项目名称:ayydio,代码行数:31,代码来源:Database.py

示例4: wrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
    def wrapper(request):
        client = MPDClient()
        try:
            client.connect(settings.MPD_HOST, settings.MPD_PORT)
            if settings.MPD_PASSWORD:
                client.password(settings.MPD_PASSWORD)
            result = func(client) or {'success': True}
        except (MPDError, IOError) as e:
            result = {
                'success': False,
                'error': _(
                    'Error while executing %(command)s: %(error_message)s'
                ) % {'command': func.__name__, 'error_message': e}
            }
        finally:
            try:
                client.close()
                client.disconnect()
            except ConnectionError:
                pass

        # add a success key in the result dict if not already present.
        result.setdefault('success', True)

        json = simplejson.dumps(result)
        return HttpResponse(json, mimetype='application/json')
开发者ID:tutuca,项目名称:vortex,代码行数:28,代码来源:views.py

示例5: mpd_status

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
def mpd_status():
    client = MPDClient()
    client.timeout = 10
    client.idletimeout = None
    client.connect("lounge.mpd.shack", 6600)
    answer = client.currentsong()
    state = client.status()
    client.close()
    client.disconnect()
    if 'artist' in answer:
        return jsonify(artist = answer['artist'],
                   title = answer['title'],
                   status = state['state'],
                   stream = 'false')
    elif 'name' in answer:
        return jsonify(name=answer['name'],
                       title=answer['title'],
                       stream='true',
                       status = state['state'])
    elif 'file' in answer:
        return jsonify(title=answer['file'],
                       status = state['state'],
                       stream='undef')
    else:
        return jsonify(error='unknown playback type')
    return jsonify(error='unknown playback type')
开发者ID:shackspace,项目名称:gobbelz,代码行数:28,代码来源:routes.py

示例6: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
class Player:
	def __init__(self):
	    self.client = MPDClient()
	    self.client.connect("localhost", 6600)
	    self.client.timeout = 10
	    self.client.idletimeout = None 


	def quit(self):
	    self.client.close()
	    self.client.disconnect()

	def get_playlists(self):
	    val = self.client.listplaylists()
	    return val

	def get_playing(self):
		name = "unknown"
		val = self.client.playlistinfo()
		if(len(val)>0):
			print val[0]
			name = val[0]["name"]

		return name

	def load(self,list):
		print "loading list", list
		self.client.clear()
		self.client.load(list)

	def play(self):
		self.client.play()

	def stop(self):
		self.client.stop()
开发者ID:KarlNewark,项目名称:pyPlaylist,代码行数:37,代码来源:mpc.py

示例7: onevent

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
def onevent(msg):
    # add song if needed
    client = MPDClient()
    client.connect("localhost", 6600)
    client.use_unicode = True
    if client.status()["playlistlength"] == '0' and autoaddstate == 1:
        song = choose_from_list(current_list)
        client.add(song)
        # while client.status()['state']=='stop':
        client.play()

    # currentsong info
    if 'player' in msg or 'playlist' in msg:
        print("publish currentsong")
        currentsong = client.currentsong()
        print(currentsong)
        # pre-treat the data if artist/title not present:
        if 'title' not in currentsong.keys():
            currentsong['artist'] = "?"
            if 'file' in currentsong.keys():
                currentsong['title'] = currentsong['file'].split('/')[-1]
        yield app.session.publish('radio.updatesong', currentsong)

        # player status info
    if ('player' in msg or
            'mixer' in msg or
            'options' in msg or
            'playlist' in msg):
        print("publish player status")
        status = client.status()
        status[u'autoadd'] = autoaddstate
        yield app.session.publish('radio.updatestatus', status)

    # playlist info
    if 'playlist' in msg:
        print("publish playlist")
        playlist = client.playlistinfo()
        print(playlist)
        playlist_trim = []
        for song in playlist:
            song_trim = {}
            if 'http' in song['file']:
                song_trim['artist'] = song['file']
                song_trim['title'] = ''
                song_trim['time'] = 9999
                song_trim['id'] = song['id']
            else:
                if 'title' not in song.keys() or 'artist' not in song.keys():
                    song_trim['artist'] = "?"
                    if 'file' in song.keys():
                        song_trim['title'] = song['file'].split('/')[-1]
                else:
                    song_trim['artist'] = song['artist']
                    song_trim['title'] = song['title']
                song_trim['id'] = song['id']
                song_trim['time'] = song['time']
            playlist_trim.append(song_trim)
        yield app.session.publish('radio.updateplaylist', playlist_trim)

    client.close()
开发者ID:crazyiop,项目名称:hipsterRadio,代码行数:62,代码来源:autoadd_update.py

示例8: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
class MPDCli:
    def __init__(self, ipaddress):
        self.client = MPDClient()
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(ipaddress, 6600)
        self.client.consume(0)

        self.ip = ipaddress

    def close(self):
        self.client.close()
        self.client.disconnect()

    def __tryConnect(self):
        try:
            self.client.update()
        except ConnectionError:
            self.client.connect(self.ip, 6600)
            self.client.update()

    def getNowPlaying(self):
        self.__tryConnect()
        return self.client.currentsong()

    def getCurrentStatus(self):
        self.__tryConnect()
        return self.client.status()

    def play(self):
        self.__tryConnect()

        currentState = self.client.status()['state']

        if currentState == 'stop':
            self.client.play(int(self.client.status()['song']))
        else:
            self.client.pause()

        return self.client.status()

    def stop(self):
        self.__tryConnect()
        self.client.stop()
        return self.client.status()

    def prev(self):
        self.__tryConnect()
        self.client.previous()
        return self.client.status()

    def next(self):
        self.__tryConnect()
        self.client.next()
        return self.client.status()

    def idle(self):
        self.__tryConnect()
        self.client.idle()
开发者ID:mikdsouza,项目名称:PyPiMPD,代码行数:61,代码来源:MPDC.py

示例9: MPDPoller

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
class MPDPoller(object):
    def __init__(self, host='localhost', port='6600', password=None):
        self._host = host
        self._port = port
        self._password = password
        self._client = MPDClient()
        
    def connect(self):
        try:
            self._client.connect(self._host, self._port)
        except IOError as strerror:
            raise PollerError("Could not connect to '%s': %s" %
                              (self._host, strerror))
        except mpd.MPDError as e:
            raise PollerError("Could not connect to '%s': %s" %
                              (self._host, e))

        if self._password:
            try:
                self._client.password(self._password)

            # Catch errors with the password command (e.g., wrong password)
            except mpd.CommandError as e:
                raise PollerError("Could not connect to '%s': "
                                  "password commmand failed: %s" %
                                  (self._host, e))

            # Catch all other possible errors
            except (mpd.MPDError, IOError) as e:
                raise PollerError("Could not connect to '%s': "
                                  "error with password command: %s" %
                                  (self._host, e))
    def disconnect(self):
        try:
            self._client.close()
        except (mpd.MPDError, IOError):
            pass
        
        try:
            self._client.disconnect()
        except (mpd.MPDError, IOError):
            self._client = mpd.MPDClient()
            
    def poll(self):
        try:
            song = self._client.currentsong()
        except (mpd.MPDError, IOError):
            self.disconnect()
            try:
                self.connect()
            except PollerError as e:
                raise PollerError("Reconnecting failed: %s" % e)
            
            try:
                song = self._client.currentsong()
            except (mpd.MPDError, IOError) as e:
                raise PollerError("Couldn't retrieve current song: %s" % e)
            
        print(song)
开发者ID:silkecho,项目名称:glowing-silk,代码行数:61,代码来源:silkmpd.py

示例10: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
class Player:
	def __init__(self):
	    self.client = MPDClient()
	    self.client.connect("localhost", 6600)
	    self.client.timeout = 10
	    self.client.idletimeout = None


	def quit(self):
	    self.client.close()
	    self.client.disconnect()

	def get_playlists(self):
	    val = self.client.listplaylists()
	    return val

	def get_stats(self):
		#{'playtime': '848', 'uptime': '2565'}
		#{'songid': '33', 'playlistlength': '1', 'playlist': '86', 'repeat': '0',
		#'consume': '0', 'mixrampdb': '0.000000', 'random': '0', 'state': 'play',
		# 'elapsed': '7.476', 'volume': '-1', 'single': '0', 'time': '7:0', 'song': '0', 'audio': '44100:16:2', 'bitrate': '128'}
		all = {}
		all.update(self.client.stats())
		all.update(self.client.status())

		stats = {}
		stats["elapsed"] = all["elapsed"] if all.has_key("elapsed") else "0"
		stats["state"] = all["state"] if all.has_key("state") else "stopped"
		stats["playtime"] = all["playtime"]
		stats["uptime"] = all["uptime"]
		stats["bitrate"] = all["bitrate"] if all.has_key('bitrate') else 0
		stats["playlistlength"] = all["playlistlength"] if all.has_key("playlistlength") else 0
		stats["song"] = all["song"] if all.has_key("song") else 0
		# print stats
		return stats

	def get_playing(self):
		name = "unknown"
		val = self.client.currentsong()
		name= val["name"] if val.has_key('name') else None
		name= val["title"] if val.has_key('title') else name
		# print val
		return name

	def load(self, list):
		# print "loading list", list
		self.client.clear()
		self.client.load(list)

	def next(self):
		self.client.next()
	def prev(self):
		self.client.previous()

	def play(self):
		self.client.play()

	def stop(self):
		self.client.stop()
开发者ID:alexellis,项目名称:pyPlaylist,代码行数:61,代码来源:mpc.py

示例11: schedule_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
def schedule_playlist(playlist_name):
    client = MPDClient()
    client.connect(settings.MPD_SERVER, settings.MPD_PORT)
    client.clear()
    client.load(playlist_name)
    client.play(1)
    client.close()
    client.disconnect()
开发者ID:Horrendus,项目名称:radiocontrol,代码行数:10,代码来源:tasks.py

示例12: excuteCommand

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
    def excuteCommand(con, channel, user, message, isMod, isSub):
	    client = MPDClient()
	    client.timeout = 10
	    client.idletimeout = None
	    client.connect("bluesnogbox.duckdns.org", 6600)
	    send_message(con, channel, 'mpd version: ' + client.mpd_version)
	    client.close()
	    client.disconnect()
开发者ID:janusnic,项目名称:Twitch-Chat-Bot,代码行数:10,代码来源:Commands.py

示例13: _mopidy_idle

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
    def _mopidy_idle(self):
        client_idle = MPDClient()
        client_idle.connect(MOPIDY_HOST, MOPIDY_PORT)
        while client_idle.status()['state'] != "stop":
            client_idle.idle()

        client_idle.close()
        client_idle.disconnect()
开发者ID:cthit,项目名称:playIT-grails,代码行数:10,代码来源:playIT_client.py

示例14: stopMPD

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
def stopMPD():
    """ Stop MPD """
    client = MPDClient()               # create client object
    client.connect("localhost", 6600)  # connect to localhost:6600
    client.clear()
    client.stop()
    client.close()
    client.disconnect()                # disconnect from the server
开发者ID:jeromefiot,项目名称:web_apiclock,代码行数:10,代码来源:functions.py

示例15: dir_to_list

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import close [as 别名]
def dir_to_list(dir):
    client = MPDClient()
    client.connect("localhost", 6600)
    client.use_unicode = True
    lst = client.lsinfo(""+dir)
    client.close()
    out = [x["file"] for x in lst if "file" in x.keys()]
    return out
开发者ID:crazyiop,项目名称:hipsterRadio,代码行数:10,代码来源:autoadd_update.py


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