• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mpd.MPDClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: run

def run():
	if not request.form['url']:
		flash('Please provide an URL')
		return redirect(url_for('welcome'))
	# do stuff
	try:
		p = subprocess.check_output(['/usr/bin/python', 'youtube-dl', '-t', '--no-progress', '--extract-audio', '--max-quality=18', '--audio-format=mp3', '--', request.form['url']])
	except:
		flash("Nice try.")
		return redirect(url_for('welcome'))
	m = re.search("\[ffmpeg\] Destination: (.+?)\s", p)
	myfile = m.group(1)
	shutil.move(myfile, "static/%s" % myfile)
	try:
		mpd = MPDClient()
		try:
			mpd.connect(host="trillian", port="6600")
			mpd.add("http://toolbox.labor.koeln.ccc.de/static/%s" % myfile)
		except:
			raise
	except:
		flash('mpd failure')
		return redirect(url_for('welcome'))
	flash('your song has been added to the playlist')
	return redirect(url_for('welcome'))
开发者ID:MechanisM,项目名称:youconv,代码行数:25,代码来源:youconv.py


示例2: fav_song

def fav_song(request):
    c = MPDClient()
    c.connect("localhost", 6600)
    form = FavSongForm(request.POST or None)
    if not form.is_valid():
        for error in form.errors:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: {0}".format(form.errors[error][0])
            )
    else:
        filename = form.cleaned_data['filename']
        track = get_track(filename, in_playlist=False)
        if not track:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: Cannot find song."
            )
        else:
            messages.add_message(
                request,
                messages.INFO,
                "Faved: {artist} - {title}".format(
                    artist=track['artist'], title=track['title'])
            )
            song_obj = get_song(filename, track['artist'], track['title'])
            SongFav(song=song_obj).save()
    return redirect(request.GET.get("from", "/"))
开发者ID:allo-,项目名称:mpdsongvote,代码行数:30,代码来源:views.py


示例3: play_id

 def play_id(play_id):
     client = MPDClient()
     client.connect(app.config['MPD']['host'], app.config['MPD']['port'])
     client.timeout = None
     client.idletimeout = None
     client.playid(play_id)
     return redirect(url_for('player'))
开发者ID:thepartyplatypus,项目名称:Touchscreen-Automation,代码行数:7,代码来源:run.py


示例4: __enter__

 def __enter__(self):
     client = MPDClient(use_unicode=True)
     self.client = client
     client.timeout = 1
     client.idletimeout = None
     client.connect("131.urlab.be", 6600)
     return client
开发者ID:UrLab,项目名称:api,代码行数:7,代码来源:views.py


示例5: request_song

def request_song(request):
    c = MPDClient()
    c.connect("localhost", 6600)
    form = RequestSongForm(request.POST or None)
    if not form.is_valid():
        for error in form.errors:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: {0}".format(form.errors[error][0])
            )
    else:
        filename = form.cleaned_data['filename']
        track = get_track(filename, in_playlist=False)
        if not track:
            messages.add_message(
                request,
                messages.ERROR,
                "Error: Cannot find song."
            )
        else:
            messages.add_message(
                request,
                messages.INFO,
                "Requested: {artist} - {title}".format(
                    artist=track['artist'], title=track['title'])
            )
            song_obj = get_song(filename, track['artist'], track['title'])
            sr, created = SongRequest.objects.get_or_create(
                song=song_obj,
            )
            sr.save()  # safe SongRequest anyway to update timestamp
            SongRequestVote(songrequest=sr, value=+1).save()
    return redirect(request.GET.get("from", "/"))
开发者ID:allo-,项目名称:mpdsongvote,代码行数:34,代码来源:views.py


示例6: yoinkMPD

def yoinkMPD(cod):
    mpd = MPDClient(use_unicode=True)
    mpd.timeout = None
    mpd.idletimeout = None
    mpd.connect(cod.config["mpd"]["host"], cod.config["mpd"]["port"])

    return mpd
开发者ID:Xe,项目名称:code,代码行数:7,代码来源:mpdclient.py


示例7: delegateInput

 def delegateInput(self, text):
     """A wrapper for querying brain."""
     got_hit = False
     # check if input is meant to start the music module
     if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
         # check if mpd client is running
         try:
             client = MPDClient()
             client.timeout = None
             client.idletimeout = None
             client.connect("localhost", 6600)
         except:
             self.logger.warning("Failed to init MPDClient")
             self.mic.say("Wybacz, ale najwyraźniej usługa Spotify nie działa")
             return
         
         self.logger.info("waiting for Spotify playlist")
         self.mic.say("Poczekaj chwilę, wczytuję listę utworów Spotify")
         music_mode = MusicMode(self.persona, self.mic, self.logger)
         music_mode.handleForever()
         return
     else:
       if " następnie " in lowerUTF8(text):
         l_text = text.split(" następnie ")
         for text in l_text:
           new_got_hit = self.brain.query(text)
           got_hit = got_hit or new_got_hit
       else:
         got_hit = self.brain.query(text)
     return got_hit
开发者ID:HubertReX,项目名称:jasper-client,代码行数:30,代码来源:conversation.py


示例8: IndiMPDClient

class IndiMPDClient(object):
	def __init__(self):
		self.config = IndiMPCConfiguration()
	
		self.setup_dbus()
		self.setup_client()
		self.oldstatus = ""
		self.oldsongdata = ""

		pynotify.init("indimpc")
		self.notification = pynotify.Notification("indiMPC started")
		self.notification.set_hint("action-icons", True)
		gobject.timeout_add(500, self.status_loop)

		if self.config.general_grab_keys:
			self.grab_mmkeys()

	def setup_dbus(self):
		dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
		self.bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
	
	def setup_client(self):
		global MPD
		try:
			self.mpdclient = MPDClient()
			self.mpdclient.connect(self.config.mpd_host, self.config.mpd_port)
			if self.config.mpd_password not in ("", None):
				self.mpdclient.password(self.config.mpd_password)
			self.oldstatus = self.mpdclient.status()["state"]
		except socket.error, e:
			sys.stderr.write("[FATAL] indimpc: can't connect to mpd. please check if it's running corectly")
			sys.exit()
开发者ID:ThomasAdam,项目名称:indimpc,代码行数:32,代码来源:indimpc.py


示例9: connect

	def connect(self,port):
		global client
		connection = False
		retry = 2
		while retry > 0:
			client = MPDClient()	# Create the MPD client
			try:
				client.timeout = 10
				client.idletimeout = None
				client.connect("localhost", port)
				log.message("Connected to MPD port " + str(port), log.INFO)
				connection = True
				retry = 0
			except:
				log.message("Failed to connect to MPD on port " + str(port), log.ERROR)
				time.sleep(0.5)	# Wait for interrupt in the case of a shutdown
				log.message("Restarting MPD",log.DEBUG)
				if retry < 2:
					self.execCommand("service mpd restart") 
				else:
					self.execCommand("service mpd start") 
				time.sleep(2)	# Give MPD time to restart
				retry -= 1

		return connection
开发者ID:MicroSDHC,项目名称:piradio,代码行数:25,代码来源:radio_class.py


示例10: delegateInput

    def delegateInput(self, texts):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        for text in texts:
            if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
                self._logger.debug("Preparing to start music module")
                # check if mpd client is running
                try:
                    client = MPDClient()
                    client.timeout = None
                    client.idletimeout = None
                    client.connect("localhost", 6600)
                except:
                    self._logger.critical("Can't connect to mpd client, cannot start music mode.", exc_info=True)
                    self.mic.say(
                        "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                    return

                self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
                self._logger.debug("Starting music mode")
                music_mode = MusicMode(self.persona, self.mic)
                music_mode.handleForever()
                self._logger.debug("Exiting music mode")
                return

        self.brain.query(texts)
开发者ID:gregnorth,项目名称:jasper-client,代码行数:27,代码来源:conversation.py


示例11: connect_to_mpd

 def connect_to_mpd(self):
     client=MPDClient()
     try:
         client.connect(MPDHost, MPDPort)
         return client
     except SocketError:
         print "Unable to connect to MPD on %s on port %s" % (MPDHost, MPDPort)
开发者ID:parth115,项目名称:mpd-tweet,代码行数:7,代码来源:mpd-tweet.py


示例12: connect

def connect(host):
    '''
    Connect to mpd.
    '''
    logger.info("Connecting to mpd on " + host)
    # Parse the host address
    url = urlparse('//' + host)

    hostname = url.hostname
    port = url.port

    # Default to localhost port 6600
    if hostname == None:
        hostname = 'localhost'
    if port == None:
        port = 6600

    logger.debug('Hostname: ' + hostname)
    logger.debug('Port: ' + str(port))

    try:
        mpdc = MPDClient()
        mpdc.connect(hostname, port)
        logger.debug('Connection succeeded')
        logger.debug('MPD status: ' + str(mpdc.status()))
    except OSError as exception:
        logger.info('Can not connect to mpdd on ' + host)
        logger.debug('Exception: ' + str(exception.errno))
        logger.debug('Message: ' + exception.strerror)
        sys.exit(1)

    return(mpdc)
开发者ID:deadbok,项目名称:RadioPi,代码行数:32,代码来源:mpd.py


示例13: MPDPoller

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,代码行数:59,代码来源:silkmpd.py


示例14: currentTrack

    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,代码行数:59,代码来源:mpd_status.py


示例15: Observer

class Observer(QThread):
    """MPD Observer thread."""
    def __init__(self):
        self._config = ServiceLocator.getGlobalServiceInstance(ServiceNames.Configuration)
        self.client = MPDClient()

        return QThread.__init__(self)

    def __del__(self):
        self.wait()

    def mpdConnect(self):
        self.client.timeout = 10
        self.client.idletimeout = None
        self.client.connect(self._config.mpdserver, self._config.mpdport)
        if len(self._config.mpdpassword) > 0:
            self.client.password(self._config.mpdpassword)
        self.client.update()

    def run(self):
        try:
            self.mpdConnect()
    
            while True:
                info = self.client.idle()
                print("info:{0}".format(info))
                if 'update' in info:
                    # Update all
                    self.updatePlaylist()
                    self.updatePlayer()
                    self.updateMixer()

                if 'playlist' in info:
                    self.updatePlaylist()
                if 'player' in info:
                    self.updatePlayer()
                    self.updateMixer()
                if 'mixer' in info:
                    self.updateMixer()
                self.sleep(2)
        except:
             self.emit(SIGNAL(ObserverSignals.ConnectionError))
            

        pass

    def updatePlaylist(self):
        playlist = self.client.playlistinfo()
        self.emit(SIGNAL(ObserverSignals.PlaylistChanged), playlist)
        pass
    def updateMixer(self):
        status = self.client.status()
        self.emit(SIGNAL(ObserverSignals.MixerChanged), status)
        pass

    def updatePlayer(self):
        currentSong = self.client.currentsong()
        self.emit(SIGNAL(ObserverSignals.PlayerChanged), currentSong)
        pass
开发者ID:huvermann,项目名称:CuteMpd,代码行数:59,代码来源:Observer.py


示例16: connect

 def connect(self, timeout=None):
   try:
     MPDClient.connect(self, host = self.__host, port = self.__port, timeout = self.__timeout)
     self.is_connected = True
   except SocketError:
     log.critical('Could not connect to MPD server')
     self.is_connected = False
   return self.is_connected
开发者ID:arsac,项目名称:pimmer,代码行数:8,代码来源:mpd_client.py


示例17: _mopidy_idle

    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,代码行数:8,代码来源:playIT_client.py


示例18: mpd_status

def mpd_status(room):
    if not room in mpd_room_to_port:
        return jsonify({'error': 'unkown room'})
    from mpd import MPDClient
    client = MPDClient()
    client.connect('mpd.shack', mpd_room_to_port[room])
    state = client.status()['state']
    return jsonify({'status': state})
开发者ID:shackspace,项目名称:shackapi,代码行数:8,代码来源:shackapi.py


示例19: initialize_mpd

def initialize_mpd(config):
    """
    Return a MPD client connection
    """
    client = MPDClient()
    client.connect(config.mpd.host, config.mpd.port)

    return client
开发者ID:thesquelched,项目名称:suggestive,代码行数:8,代码来源:mstat.py


示例20: stop_radio

def stop_radio():
    client = MPDClient()
    client.timeout = MPD_TIMEOUT
    client.connect(MPD_SERVER, 6600)
    client.stop()
    client.close()
    client.disconnect()

    return ""
开发者ID:j4y-funabashi,项目名称:orac,代码行数:9,代码来源:orac.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mpdhelper.call函数代码示例发布时间:2022-05-27
下一篇:
Python mparser.ProfileParser类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap