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


Python MPDClient.disconnect方法代码示例

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


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

示例1: wrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例2: play_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
def play_playlist(name):
    client=MPDClient()
    mopidyAddress = 'localhost'
    mopidyPort = 6600

    client.timeout = 10
    client.idletimeout = None
    client.connect(mopidyAddress,mopidyPort)
    #client.password('IlPits2013')
    client.clear()
    if playlist_exists(name):
        client.load(name)
    spotify_lists = get_spotify_playlists()
    name = name.encode('utf-8')
    print name
    #print spotify_lists
    if name in spotify_lists:
        add_spotify_directory(name)
    #time.sleep(1)
    if name == 'Pierre':
        client.shuffle()

    #client.setvol(50)
    #client.play()
    client.disconnect()
    return
开发者ID:NilsNoreyson,项目名称:phoneBookServer,代码行数:28,代码来源:get_phonebook_files.py

示例3: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例4: wrapper

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例5: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例6: mpd_status

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例7: print_files

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
def print_files():
    sync_files = open('/media/satellite_mpds/files2sync.txt','a')
    client=MPDClient()
    mopidyAddress = 'localhost'
    mopidyPort = 6600

    client.timeout = 10
    client.idletimeout = None
    client.connect(mopidyAddress,mopidyPort)
    #client.password('IlPits2013')
    files = client.playlistinfo()
#    files = client.lsinfo(foldername)
    files = [x['file'] for x in files]
    files = sorted(files)
    outfiles=[]
    for f in files:
        real_path=os.path.join(music_dir,f)
        if os.path.exists(real_path):
            if os.path.islink(real_path):
                target_path = os.readlink(real_path)
                abs_target_path = os.path.realpath(real_path)
                target_path_rel_to_music_dir = os.path.relpath(abs_target_path, music_dir)
                print target_path_rel_to_music_dir
                sync_files.write(target_path_rel_to_music_dir+'\n')
                outfiles.append(target_path_rel_to_music_dir)
            sync_files.write(f+'\n')
            outfiles.append(f)
            print('ADDED')
            print f
    sync_files.close()
    #print(files)
    client.disconnect()
开发者ID:NilsNoreyson,项目名称:phoneBookServer,代码行数:34,代码来源:get_phonebook_files.py

示例8: main

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
def main():
    ## MPD object instance
    client = MPDClient()
    if mpdConnect(client, CON_ID):
        print('Got connected!')
    else:
        print('fail to connect MPD server.')
        sys.exit(1)

    # Auth if password is set non False
    if PASSWORD:
        if mpdAuth(client, PASSWORD):
            print('Pass auth!')
        else:
            print('Error trying to pass auth.')
            client.disconnect()
            sys.exit(2)

    ## Fancy output
    pp = pprint.PrettyPrinter(indent=4)

    ## Print out MPD stats & disconnect
    print('\nCurrent MPD state:')
    pp.pprint(client.status())

    print('\nMusic Library stats:')
    pp.pprint(client.stats())

    client.disconnect()
    sys.exit(0)
开发者ID:HikaruLim,项目名称:python-mpd2,代码行数:32,代码来源:stats.py

示例9: MPDPoller

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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 disconnect [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

示例11: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例12: __init__

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
class MpdState:
    """
    Displays MPD state, name of current song, number, etc.
    :parameters:
        host : str
            host name of the MPD server
        port : int
            port number to connect to server
        password : str
            password
    The following keys are returned:
        mpdstate : MPD state, playing/stopped/paused
    """

    def __init__(self, host="localhost", port=6600, password=""):
        self.host = host
        self.port = str(port)
        self.password = password

        self.client = MPDClient()
        self.connected = False

    def __del__(self):
        try:
            self.client.disconnect()
        except mpd.ConnectionError:
            pass

    def connect(self):
        try:
            self.client.connect(host=self.host, port=self.port)
        except SocketError:
            return False
        return True

    def auth(self):
        if self.password:
            try:
                client.password(self.password)
            except CommandError:
                return False
        return True

    def get(self):
        d = {"mpd_state": "not connected", "mpd_title": "", "mpd_track": "", "mpd_artist": ""}
        try:
            mpdState = self.client.status()["state"]
            songInfo = self.client.currentsong()
        except:
            self.connect()
            self.auth()
            return d

        d["mpd_state"] = mpdState
        if mpdState == "play":
            d["mpd_track"] = safeGet(songInfo, key="track", default="00")
            d["mpd_artist"] = safeGet(songInfo, key="artist", default="Unknown Artist")
            d["mpd_title"] = smart_truncate(safeGet(songInfo, key="title", default="Unknown Title"), max_length=42)
        return d
开发者ID:ajaybhatia,项目名称:archlinux-dotfiles,代码行数:61,代码来源:specbar.py

示例13: currentTrack

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
    def currentTrack(self, i3status_output_json, i3status_config):
        try:
            c = MPDClient()
            c.connect(host=HOST, port=PORT)
            if PASSWORD:
                c.password(PASSWORD)

            status = c.status()
            song = int(status.get("song", 0))
            next_song = int(status.get("nextsong", 0))

            if (status["state"] == "pause" and HIDE_WHEN_PAUSED) or (status["state"] == "stop" and HIDE_WHEN_STOPPED):
                text = ""
            else:
                try:
                    song = c.playlistinfo()[song]
                    song["time"] = "{0:.2f}".format(int(song.get("time", 1)) / 60)
                except IndexError:
                    song = {}

                try:
                    next_song = c.playlistinfo()[next_song]
                except IndexError:
                    next_song = {}

                format_args = song
                format_args["state"] = STATE_CHARACTERS.get(status.get("state", None))
                for k, v in next_song.items():
                    format_args["next_{}".format(k)] = v

                text = STRFORMAT
                for k, v in format_args.items():
                    text = text.replace("{" + k + "}", v)

                for sub in re.findall(r"{\S+?}", text):
                    text = text.replace(sub, "")
        except SocketError:
            text = "Failed to connect to mpd!"
        except CommandError:
            text = "Failed to authenticate to mpd!"
            c.disconnect()

        if len(text) > MAX_WIDTH:
            text = text[-MAX_WIDTH-3:] + "..."

        if self.text != text:
            transformed = True
            self.text = text
        else:
            transformed = False

        response = {
            'cached_until': time() + CACHE_TIMEOUT,
            'full_text': self.text,
            'name': 'scratchpad-count',
            'transformed': transformed
        }

        return (POSITION, response)
开发者ID:AdamBSteele,项目名称:py3status,代码行数:61,代码来源:mpd_status.py

示例14: schedule_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [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

示例15: validate_exists_and_is_not_in_playlist

# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import disconnect [as 别名]
def validate_exists_and_is_not_in_playlist(filename):
    c = MPDClient()
    c.connect("localhost", 6600)
    if len(c.playlistfind("file", filename)):
        raise forms.ValidationError("Song is already in the playlist.")
    elif not len(c.find("file", filename)):
        raise forms.ValidationError("Song not found.")
    c.disconnect()
开发者ID:allo-,项目名称:mpdsongvote,代码行数:10,代码来源:forms.py


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