(Python):import sysimport xbmcpluginxbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category="LA CATÉGORIE DU PLUGIN" )
(Python):import sysimport xbmcplugin#la couleur doit etre en (AARRGGBB), mais peut etre videpath_img = "mon image"fanart_color1 = ""fanart_color2 = ""fanart_color3 = ""xbmcplugin.setPluginFanart( handle=int( sys.argv[ 1 ] ), image=path_img, color1=fanart_color1, color2=fanart_color2, color3=fanart_color3 )
(Python):import os ############################################################################# Get current working directory and update internal vars with it ############################################################################ # Set pathsROOTDIR = os.getcwd().replace( ";", "" ) # Create a path with valid format IMAGEDIR = os.path.join(ROOTDIR, "images")CACHEDIR = os.path.join(ROOTDIR, "cache")DOWNLOADDIR = os.path.join(ROOTDIR, "download")LIBDIR = os.path.join(ROOTDIR, "lib")
(Python):os.remove(os.path.join(DOWNLOADDIR, filename))
(Python):import urllibimport os.path def downloadJPG(source, destination): """ Source MyCine (thanks!) Download IF NECESSARY a URL 'source' (string) to a URL 'target' (string) Source is downloaded only if target doesn't already exist """ if os.path.exists(destination): pass else: try: #print("downloadJPG destination doesn't exist, try to retrieve") loc = urllib.URLopener() loc.retrieve(source, destination) except Exception, e: print("Exception while source retrieving") print(e) print (str(sys.exc_info()[0])) traceback.print_exc() pass
(Python):#Code générale pour imprimer print "ok ok je sors"
(Python):import oshome = os.getcwd().replace(';','')lib = os.path.join(home, 'sqlite3')sys.path.append(lib)import sqlite3 conn = sqlite3.connect('/home/seb/.xbmc/userdata/Database/MyVideos34.db')c = conn.cursor() c.execute('select * from movie')for champ in c: print champ
(Python):{'option1': function1, 'option2': function2, 'option3': function3, 'option4': function4}[value]()
(PHP):switch ($value) { case 'a': $result = $x * 5; break; case 'b': $result = $x + 7; break; case 'c': $result = $x - 2; break;}
(Python):result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2}[value](x)
(Python):""" There is no switch or case in Python ... because you cando better by using its OO capabilities and a dictionary. """ def doblue (): print "The sea is blue"def dogreen (): print "Grass is green"def doyellow (): print "Sand is yellow" def redflag (): print "Red is the colour of fire" print "do NOT play with fire" def errhandler (): print "Your input has not been recognised" # set up a dictionary of actions takeaction = { "blue": doblue, "green": dogreen, "yellow": doyellow, "red": redflag} colour = raw_input("Please enter red blue green or yellow ")takeaction.get(colour,errhandler)() # Uses the get method to allow us to specify a default
(Python):import xbmc xbmc.executescript('q:\\scripts\\Installeur-Passion\\default.py')
(Python):import shutilsource="q:\skins\monskin\"destination = "q:\skins\monskin_bak\try: shutil.copytree(source, destination)except: print "oups ! problème !!"
(Python):coordonnees= { "alexsolex" : ("0123456","paris") , "toto" : ("0234198548","Babeloued") , "bernard" : ("8765321","moscou") }
(Python):print coordonnees["alexsolex"]>>> ("0123456","paris")tel,ville = coordonnees["alexsolex"]print tel>>> 0123456print ville>>> paris
(Python):user = coordonnees["alexsolex"]print user[0]>>> 0123456print user[1]>>> paris
(Python):print coordonnees["alexsolex"][0]>>> 0123456print coordonnees["alexsolex"][1]>>> paris
(Python):listenoms = coordonnees.keys() #on prend les clés du dictionnaire (les noms)listenoms.sort() #on trie sur place la liste (elle se réaffecte d'elle même avec les entrées triées)for nom in listenoms: print "%s\n\ttél: %s\n\tville: %s" % (nom, coordonnees[nom][0], coordonnees[nom][1])
(Python):maliste = [ "bonjour" , 123, 45.0045, mafonction]print maliste[1]>>> 123
(Python):from string import *import xbmcgui # Recuperation d'un texte via la clavier virtuelkeyboard = xbmc.Keyboard("", heading = "Saisir votre Texte")keyboard.setHeading('Texte a saisir') # En tetekeyboard.setDefault("Mon texte par defaut") # Texte par defaut qui sera deja affiche a la saisiekeyboard.doModal()if (keyboard.isConfirmed()): inputText = keyboard.getText() print"Login: %s"%inputText # on fait ce que l'on veut avec le texte saisi # ... dialogInfo = xbmcgui.Dialog() dialogInfo.ok("Texte saisi", "Votre texte est:", "%s"%inputText)del keyboard
(Python):from string import *import xbmcgui # Recuperation d'un mot de passe via la clavier virtuelkeyboard = xbmc.Keyboard("", heading = "Saisir votre Mot de passe", hidden = True)keyboard.setHeading('Mot de passe') # En tetekeyboard.setHiddenInput(True) # On cache le texte a l'ecrankeyboard.doModal()if (keyboard.isConfirmed()): inputText = keyboard.getText() # on fait ce que l'on veut avec le mot de passe saisi # ... dialogInfo = xbmcgui.Dialog() dialogInfo.ok("Mot de passe", "Votre mot de passe a bien été défini")keyboard.setHiddenInput(False) # optionaldel keyboard
(Python):from urllib import urlopenimport threadingfrom Queue import Queue, Emptyfrom time import time NUM_THREADS = 40start = time()q_in = Queue(0)q_out = Queue(0) # on remplit q_in avec les url (ici c'est juste un exemple pour tester)for i in xrange(400): q_in.put("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%d" % i) def getfiles(): # fonction exécutée par les threads # ici je me contente de sauver le contenu avec l'url dans q_out try: while True: url = q_in.get_nowait() f = urlopen(url) q_out.put((url,f.read())) f.close() except Empty: # q_in est vide; on a terminé pass # on crée et on démarre les threadsfor i in xrange(NUM_THREADS): t = threading.Thread(target = getfiles) t.start() count = 0# tant qu'il y a des threads actifs ou des résultats disponibleswhile threading.activeCount() > 1 or not q_out.empty(): try: # on retire les résultats de la queue # on attend au plus 500 ms si la queue est vide # le timeout est nécessaire pour éviter une race condition url, contents = q_out.get(True, 0.5) count += 1 print url, ':', contents except Empty: pass print "%d fichiers récupérés en %f secondes" % (count, time() - start)
(Python):listitem.addContextMenuItems([("test","XBMC.ReloadSkin()",)])
(Python):if sys.modules.has_key("Module"): reload(Module)else: import Module
(Python):if sys.modules.has_key("monmodule"): del sys.modules["monmodule"]import monmodule
(Python):CHEMIN_LIB = "q:\scripts\passion-XBMC\divers\lib\"import syssys.path.append(CHEMIN_LIB) #maitenant python cherchera aussi dans ce chemin pour y trouver les libs que tu demandes et donc :import passion #fonctionne normalement
(Python):mon_module_import = "passion"exec("import %s"%mon_module_import)
(Python):#Comment mettre de la couleur dans un texte.#note: les couleurs du themes en fonction peut etre utiliser. \skin\PM3.HD\colors\defaults.xml #<color name="green">ffe2ff43</color> qui nous donnent print "[COLOR=green"]MOT QUI VA ETRE EN VERT[/COLOR]"#remarque qu'au changement de themes on risque de perdre notre couleur qui est déffinie#Le mieux est de faire print "[COLOR=ffe2ff43]MOT QUI VA ETRE EN VERT[/COLOR]" red_color = "FFFF0000"text_color = "Rouge" label_formatting = "[COLOR=%s]%s[/COLOR]" % ( red_color, text_color, )print label_formatting text = "le feu de circulation est rouge, il faut attendre le feu vert."text = text.replace( "rouge", label_formatting ) #pourquoi pas en faire un autre text = text.replace( "vert", "[COLOR=ffe2ff43]vert[/COLOR]" )print text # Encore plus mettre un mot en gras ou en italic print "[B]bold[/B] - bold text."print "[I]italics[/I] - italic text." # Plus sur le label formatting visite le manuel xbmc: http://xbmc.org/wiki/?title=Label_Formatting
(XML):<default type="label"> <posx>80</posx> <posy>60</posy> <label>-</label> <font>font13</font> <textcolor>white</textcolor></default>
(Python):import xbmc# Execute shell commands and freezes XBMC until shell is closedcmd = "System.ExecWait" # Execute shell commands#cmd = "System.Exec" command = '%s("%s")' % ( cmd, "C:\\Program Files\\Mozilla Firefox\\firefox.exe" )xbmc.executebuiltin( command )
(Python):#pour récupérer le log level actuel (utile pour le rétablir si besoin après l'exécution du script)actualloglevel = xbmc.executehttpapi("GetLogLevel").replace("<li>","") #pour régler le loglevel sur la valeur désirée (ici à 1):status = xbmc.executehttpapi("SetLogLevel(1)").replace("<li>","")#si tout c'est bien passé, status contient "OK"
(Python):import xbmc def get_system_platform(): """ fonction: pour recuperer la platform que xbmc tourne """ platform = "unknown" if xbmc.getCondVisibility( "system.platform.linux" ): platform = "linux" elif xbmc.getCondVisibility( "system.platform.xbox" ): platform = "xbox" elif xbmc.getCondVisibility( "system.platform.windows" ): platform = "windows" elif xbmc.getCondVisibility( "system.platform.osx" ): platform = "osx" return platform
(Python):if os.environ.get( "OS", "" ).lower() == "os x": print "Platform MAC"
(Python):# If the dir exists with the requested name, simply return it __all__ = [ # public names "XBMC_IS_HOME", "SPECIAL_XBMC_DIR", "SPECIAL_HOME_DIR", "SPECIAL_TEMP_DIR", "SPECIAL_PROFILE_DIR", "SPECIAL_MASTERPROFILE_DIR", "SPECIAL_XBMC_HOME", "SPECIAL_SCRIPT_DATA", ] import osimport sysfrom xbmc import translatePath PLATFORM_MAC = os.environ.get( "OS", "" ).lower() == "os x" try: scriptname = sys.modules[ "__main__" ].__script__except: scriptname = os.path.basename( os.getcwd() ) SPECIAL_XBMC_DIR = translatePath( "special://xbmc/" )if PLATFORM_MAC or not os.path.isdir( SPECIAL_XBMC_DIR ): SPECIAL_XBMC_DIR = translatePath( "Q:\\" ) SPECIAL_HOME_DIR = translatePath( "special://home/" )if PLATFORM_MAC or not os.path.isdir( SPECIAL_HOME_DIR ): SPECIAL_HOME_DIR = translatePath( "U:\\" ) SPECIAL_TEMP_DIR = translatePath( "special://temp/" )if PLATFORM_MAC or not os.path.isdir( SPECIAL_TEMP_DIR ): SPECIAL_TEMP_DIR = translatePath( "Z:\\" ) SPECIAL_PROFILE_DIR = translatePath( "special://profile/" )if PLATFORM_MAC or not os.path.isdir( SPECIAL_PROFILE_DIR ): SPECIAL_PROFILE_DIR = translatePath( "P:\\" ) SPECIAL_MASTERPROFILE_DIR = translatePath( "special://masterprofile/" )if PLATFORM_MAC or not os.path.isdir( SPECIAL_MASTERPROFILE_DIR ): SPECIAL_MASTERPROFILE_DIR = translatePath( "T:\\" ) SPECIAL_XBMC_HOME = ( SPECIAL_HOME_DIR, SPECIAL_XBMC_DIR )[ ( os.environ.get( "OS", "xbox" ).lower() == "xbox" ) ] XBMC_IS_HOME = SPECIAL_HOME_DIR == SPECIAL_XBMC_DIR SPECIAL_SCRIPT_DATA = os.path.join( SPECIAL_PROFILE_DIR, "script_data", scriptname )if not os.path.isdir( SPECIAL_SCRIPT_DATA ): os.makedirs( SPECIAL_SCRIPT_DATA )
(Python):import xbmc # Quit Quit XBMC (same as XBMC.Dashboard on Xbox) # Suspend Suspends (S3 / S1 depending on bios setting) the System (not working on Xbox due to hardware limitations)# Hibernate Hibernate (S5) the System (not working on Xbox due to hardware limitations)# Powerdown Powerdown system# Minimize Minimize XBMC to tools barstate = { "quit": 0, "suspend": 1, "hibernate": 2, "powerdown": 4, "minimize": 5 } # print current user setting shutdownstateuser_state = xbmc.executehttpapi( "GetGuiSetting(0;system.shutdownstate)" ).replace( "<li>", "" )print user_state# force setting shutdownstate to minimizeprint xbmc.executehttpapi( "SetGUISetting(0;system.shutdownstate;%i)" % state[ "minimize" ] ).replace( "<li>", "" )# print forced setting shutdownstateprint xbmc.executehttpapi( "GetGuiSetting(0;system.shutdownstate)" ).replace( "<li>", "" ) # XBMC.ShutDown Trigger default Shutdown action defined in System Settings,# Default Powerdown on Xbox and Quit on Linux / OSX / Windowsxbmc.shutdown() # replace preference user setting shutdown stateprint xbmc.executehttpapi( "SetGUISetting(0;system.shutdownstate;%i)" % int( user_state ) ).replace( "<li>", "" )
(Python):import xbmc xbmc.executebuiltin( "XBMC.Minimize()" )
(Python):import os folder = os.getcwd().replace(';','') def del_all_files_dirs(folder): for root, dirs, files in os.walk(folder, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(folder) print '%s deleted'%folder for root, dirs, files in os.walk(folder , topdown=False): for name in dirs: print 'entering %s ...'%os.path.join(root, name) if '.svn' in name: del_all_files_dirs(os.path.join(root,name)) print 'Well done'
(Python):import osimport string def replaces( source, search_for, replace_with ): # set temporary files back = os.path.splitext( source )[ 0 ] + ".bak" temp = os.path.splitext( source )[ 0 ] + ".tmp" # remove temp file if exists try: os.remove( temp ) except os.error: pass # open source and temp file fi = open( source ) fo = open( temp, "w" ) # read lines of source file for line in fi.readlines(): # temp file, write line with replaced str fo.write( string.replace( line, search_for, replace_with ) ) # end replace close source and temp file fi.close() fo.close() # remove backup file if exists try: os.remove( back ) except os.error: pass # now rename original file into backup os.rename( source, back ) # and rename temp into new source os.rename( temp, source ) source_file = "test_replaces.xml"search_for = "Salut"replace_with = "Bonjour" replaces( source_file, search_for, replace_with )
(Python):def splitlist( iterable, start=0, step=30, end=0 ): """Return a list containing an slice of iterable. start (!) defaults to 0.; step is split index, (!) defaults to 30.; end (!) defaults to 0. For example, splitlist(range(4)) returns [[0, 1, 2, 3]]. """ try: splited = [] if end <= 0: end = len( iterable ) for index in xrange( step, end, step ): splited.append( iterable[ start:index ] ) start = index splited.append( iterable[ start:end ] ) return splited except: from traceback import print_exc print_exc() return [ iterable ]
(Python):import stringmaliste = list( string.printable )print malisteprint # splitlist( iterable, start=0, step=30, end=0 ) )splited = splitlist( maliste ) print "Nombre total d'items", len( maliste ) print "Nombre de listes", len( splited ) for count, liste in enumerate( splited ): print "liste #", count+1 print len( liste ), liste print""" >>> ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ' ', '\t', '\n', '\r', '\x0b', '\x0c'] Nombre total d'items 100Nombre de listes 4liste # 130 ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'] liste # 230 ['u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X'] liste # 330 ['Y', 'Z', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`'] liste # 410 ['{', '|', '}', '~', ' ', '\t', '\n', '\r', '\x0b', '\x0c'] >>> """
(Python):from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup((open(os.path.join(CACHEDIR, XMLFile), 'r')).read())cat_scrapers = soup.find("scrapers") if cat_scrapers != None: for item in cat_scrapers.findAll("entry"): if hasattr(item.title,'string'): if item.title.string != None: title = item.title.string.encode("cp1252") if hasattr(item.version,'string'): if item.version.string != None: version = item.version.string.encode("utf-8") if hasattr(item.lang,'string'): if item.lang.string != None: language = item.lang.string.encode("utf-8") if hasattr(item.date,'string'): if item.date.string != None: date = item.date.string.encode("cp1252") if hasattr(item.previewvideourl,'string'): if item.previewvideourl.string != None: previewVideoURL = item.previewvideourl.string.encode("utf-8")
(Python):import elementtree.ElementTree as ET elems = ET.parse( open( os.path.join( CACHEDIR, XMLFile ), "r" ) ).getroot()cat_scrapers = elems.find( "scrapers" ).findall( "entry" ) for item in cat_scrapers: title = item.findtext( "title" ) version = item.findtext( "version" ) language = item.findtext( "lang" ) date = item.findtext( "date" ) added = item.findtext( "added" ) previewVideoURL = item.findtext( "previewVideoURL" )