Here's my slightly modified random music script based on
Playlistwalker. The only other script I was able to get working required you manually generate the playlist which was undesirable in my case. Save this to scripts\autoexec.py and edit the fifth line from the bottom walkTheHD(['F:\\Music... for the directory you'd like to use. The only thing I changed from the original was the removal of dependencies on the samba library and a popup "working..." dialog.
CODE
#!/usr/bin/python
# encoding: iso-8859-1
#
# Python xbmc script
# Playlistwalker V1.3
#
# Written by thor918
# 12.Februar 2005. *Thor (Submittet to xbmc forum )
# Revised : 28.Februar 2005. *Thor (New features added )
# Revised : 04.Mars 2005. *Thor (Cleanup and new features added )
# Revised : 12.Mars 2005. *Thor (Cleanup,change in bigplaylist function)
#
# Respects:
# Michael Teo for his SMB phyton lib
# http://miketeo.net/projects/pysmb/docs/smb_smb.html
#
#
#
# Install :
# ------------
# \lib\ ->extract to q:\xbmc\phyton\lib
# \playlistwalker\ ->extract to q:\xbmc\scripts\
# \playlistwalker.py ->extract to q:\xbmc\scripts\
# ADD commands below the .Start using the walkcommands here.
# ******************************************************************************
#
# Notes:
# ------
# smbwalk have a Limitation of prossessing only 32(folder and files) in a list for every folder that is prossessed
# I guess that is a bug in the lib...
#
# About this script:
# ------------------
# Walk trough folders and leaves a playlist.m3u file
# containing a list of(mp3,jpg,avi,mov....).
# ******************************************************************************
#-------------------------------------------------------------------------
# Config start
#-------------------------------------------------------------------------
xbox = True #You can run this script on a pc if xbox is set to False
playlistnamedbyfolder = True # Playlistfilename = playlistwalker.m3u or (foldername where we are prossesing).m3u
#-------------------------------------------------------------------------
# Config end
#-------------------------------------------------------------------------
import os
import operator,string
import shutil
if (xbox == True):import xbmc, xbmcgui #We are running in xboxmode
# Global progress dialog
if (xbox == True):
#Refering dialogprg to xbox object only if we are in xboxmode
try:dialogPrg = xbmcgui.DialogProgress()
except:dialogPrg = ""
class dialogProgress(object):
#Object for progress display on xbox
def create(self,headline,text):
if (xbox == True):
self.close()
try:
dialogPrg.create(str(headline),str(text))
except:
print "No dialogprogress found,moving on"
def update(self,procent):
if (xbox == True):
if ( (int(procent) >= 0) and (int(procent) <= 100) ):
dialogPrg.update(int(procent))
def close(self):
if (xbox == True):
try:
print "Dialogprogress closed"
dialogPrg.close()
except:
print "No dialogprogress found,moving on"
class parseplaylist(object):
#Object for filehandelingcode
def __init__(self,playlistitems):
self.playlistitems = playlistitems #array of playlist file extencions
def checkplaylistfile(self,filename):
for fileext in self.playlistitems:
if (string.find(filename,'AlbumArt') <> -1) and (filename.split(".")[len(filename.split("."))-1] == 'jpg'):
# Removing album jpgs
return False
if (filename == 'Folder.jpg'):
# Removing album jpgs
return False
#You can add more checks to discard more files here
if filename.split(".")[len(filename.split("."))-1] == fileext:
return True
return False
def isplaylistfile(self,filename):
if filename.split(".")[len(filename.split("."))-1] == "m3u":
return True
class parsepath(object):
#Object for parsing a path
def __init__(self,data):
self.path = data
def getshare(self):
return operator.getslice(self.path,0, string.find(self.path, '\\'))
def getpathwithoutshare(self):
return operator.getslice(self.path,string.find(self.path, '\\')+1, string.rfind(self.path, '\\'))
def getpath(self):
return operator.getslice(self.path,0, string.rfind(self.path, '\\'))
def getfile(self):
return operator.getslice(self.path,string.rfind(self.path, '\\')+1, len(self.path))
def getfolder(self):
#Quick fix to get the playlistfile name
if (playlistnamedbyfolder==True):
if (string.rfind(self.path, ':')==-1):
#share d = 1
if (len(string.replace(self.path, '\\', '')) == 1):
#Root
return 'playlistwalker'
else:
#Folder
return operator.getslice(self.path,string.rfind(self.path, '\\')+1, len(self.path))
else:
#hd d: = 2
if (len(string.replace(self.path, '\\', '')) == 2):
#Root
return 'playlistwalker'
else:
#Folder
if ( operator.getslice( self.path,len(self.path)-1,len(self.path) ) == "\\" ):
self.path = operator.getslice( self.path,0,len(self.path)-1)
return operator.getslice(self.path,string.rfind(self.path, '\\')+1, len(self.path))
else:
return 'playlistwalker'
def slashfix(self):
# Add \\ after the drive letter, and remove any double slashes
return string.replace(string.replace(self.path, ':', ':\\'),'\\\\','\\')
def getfolderinprogress(self):
#Return folder in progressdialog
if (operator.getslice(self.path,string.rfind(self.path, '\\')+1, len(self.path)) == ''):
#We are walking mostlikly in the root of a drive
return 'playlistwalker'
else:
return operator.getslice(self.path,string.rfind(self.path, '\\')+1, len(self.path))
class fileobject(object):
#Object for filehandelingcode
def __init__(self):
self.content = None
def writecontent(self,data):
self.content = data
def getcontent(self):
return str(self.content)
def getbincontent(self):
return self.content
def tempfoldercheck(self):
if (os.path.exists ('Q:\\scripts\\playlistwalker\\') != True):
print "Tempdir does not exist, we create it"
os.mkdir('Q:\\scripts\\playlistwalker\\')
class CleanTheHD(object):
def __init__(self,patharray):
print "We are walking a harddrive"
if ( len(patharray) == 1 ):
path = parsepath(patharray[0]).slashfix()
else:
return False
for root, dirs, files in os.walk( path ):
mappeliste = os.listdir(root) # Print : Mappa vi sjekker naa
walkpath = parsepath(root).slashfix()
dialogProgress().create("PlaylistWalker", "Cleaning playlists..." + parsepath(root).getfolderinprogress())
for i in range(0, len(mappeliste)):
if os.path.isfile(root + "\\" + mappeliste):
if ( parseplaylist('').isplaylistfile(mappeliste) ):
print "vi sletter en "
os.remove(parsepath(walkpath + "\\" + mappeliste).slashfix() )
perc = int ( (i/len(mappeliste))*100)
dialogProgress().update(perc)
dialogProgress().close()
class walkTheHD(object):
def __init__(self,patharray,playlistitems):
print "We are walking a harddrive"
self.playlistitems = playlistitems
count = 0
path = ""
biglistpath = ""
if ( len(patharray) == 1 ):
path = parsepath(patharray[0]).slashfix()
else:
if( len(patharray) == 2 ):
path = parsepath(patharray[0]).slashfix()
biglistpath = parsepath(patharray[1]).slashfix()
else:
return False
fileobject().tempfoldercheck() #create tempfolder
if os.path.isfile('Q:\\scripts\\playlistwalker\\playlistwalker.m3u'):
print "vi sletter en eksisterende playlist playlistwalker.m3u"
os.remove('Q:\\scripts\\playlistwalker\\playlistwalker.m3u')
for root, dirs, files in os.walk( path ):
mappeliste = os.listdir(root) # Print : Mappa vi sjekker naa
walkpath = parsepath(root).slashfix()
if (len(biglistpath)==0):
count = 0
if os.path.isfile('Q:\\scripts\\playlistwalker\\playlistwalker.m3u'):
print "vi sletter en eksisterende playlist playlistwalker.m3u"
os.remove('Q:\\scripts\\playlistwalker\\playlistwalker.m3u')
for i in range(0, len(mappeliste)):
if os.path.isfile(root + "\\" + mappeliste):
if parseplaylist(self.playlistitems).checkplaylistfile( mappeliste ):
if not os.path.isfile('Q:\\scripts\\playlistwalker\\playlistwalker.m3u'): # sjekker om vi har en generert liste i mappa fra for
file('Q:\\scripts\\playlistwalker\\playlistwalker.m3u', 'w').write('')
file('Q:\\scripts\\playlistwalker\\playlistwalker.m3u', 'a').write( parsepath(walkpath + "\\" + mappeliste + "\n").slashfix() )
count = count + 1
perc = int( ( i/len(mappeliste) )*100)
dialogProgress().update(perc)
if ( ( count!=0 ) and ( len(biglistpath)==0 ) ):
print "Copy over the file"
try:shutil.copyfile( 'Q:\\scripts\\playlistwalker\\playlistwalker.m3u', parsepath(walkpath + "\\" + parsepath(walkpath).getfolder() + '.m3u').slashfix() )
except:print "Copy over the file, error"
dialogProgress().close()
if ( ( count!=0 ) and ( len(biglistpath)!=0 ) ):
print "Copy over the bigfile " + biglistpath
try:shutil.copyfile('Q:\\scripts\\playlistwalker\\playlistwalker.m3u', parsepath(biglistpath).slashfix() )
except:print "Copy over the file, error"
class walkTheSMB(object):
def __init__(self,patharray,hostname,hostip,username,password,playlistitems):
if ( len(patharray) == 1 ):
path = parsepath(patharray[0]).slashfix()
else:
return False
self.playlistitems = playlistitems
self.lastpath = ''
print 'Connecting to share................'
self.remote = smb.SMB(hostname , hostip )
self.remote.login(username, password)
if ( operator.getslice( path,len(path)-1,len(path) ) != "\\" ):
#We are missing the last slash.lets add it
path += "\\"
fileobject().tempfoldercheck() #create tempfolder
self.query_path(self.remote, parsepath(path).getshare(), parsepath(path).getpathwithoutshare(), 0, password)
def copyfile(self,path,newpath):
#Path = local file path, d:\\pictures\\test.jpg
#Newpath = destination full share path d\\pictures\\test.jpg
filedata = fileobject()
newpath = parsepath(newpath).slashfix()
try:
filedata.writecontent( open(path, 'rb').read )
except:
return -1#Error code -1 file open error
try:
self.remote.stor_file( parsepath(newpath).getshare(), "\\" + parsepath(newpath).getpathwithoutshare() + "\\" + parsepath(newpath).getfile(), filedata.getbincontent())
return 1 #Success
except:
return -2#Error code -2 file transfer error
def query_path(self,s, share, path, depth, password):
global lastpath
dirarray = []
count = 0
perc = 0
try:
listings = s.list_path(share, path + '/*', password = password)
dialogProgress().create("PlaylistWalker", "Generating playlists..." + parsepath(path).getfolderinprogress())
for f in listings:
if f.get_longname() != '.' and f.get_longname() != '..':
if f.is_directory():
dirarray.append(path + '\\' + f.get_longname()) #add directory for later prossesing
else:
if self.lastpath <> (share + '\\' + path):
print 'Newdir start delete temp m3u file'
try:
os.remove('Q:\\scripts\\playlistwalker\\playlistwalker.m3u')
except:
print 'ERROR in deltetion of playlist'
self.lastpath = share + '\\' + path
print share + '\\' + path + '\\' + f.get_longname()
if parseplaylist(self.playlistitems).checkplaylistfile( f.get_longname() ):
#We have a playlistitem
try:
if not os.path.isfile('Q:\\scripts\\playlistwalker\\playlistwalker.m3u'): # sjekker om vi har en generert liste i mappa fra for
file('Q:\\scripts\\playlistwalker\\playlistwalker.m3u', 'w').write('') # Oppretter playlist
file('Q:\\scripts\\playlistwalker\\playlistwalker.m3u' , 'a').write( f.get_longname() + "\n")
count = count + 1
except:
print 'Error in playlist creation'
perc = int ( (float(count+1)/float(len(listings)+1))*100)
dialogProgress().update(perc)
dialogProgress().close()
try:
if count <> 0:
print '2,Uploaded a file :' + str( self.copyfile( 'Q:\\scripts\\playlistwalker\\playlistwalker.m3u' ,parsepath(share + '\\' + path + '\\' + parsepath(path).getfolder() + '.m3u').slashfix() ) )
else:
print 'No files found in this folder,check next'
except:
print 'Error in Playlist upload'
for f in dirarray:
self.query_path(s, share, f, depth + 1, password)
except smb.SessionError, ex:
print 'Warning: Cannot list', path
print ex[0], ':', smb.strerror(ex[1], ex[2])[1]
#-------------------------------------------------------------------------
# Commandlist V1.3 12.Mars 2005
#-------------------------------------------------------------------------
# Cleaning playlists on Harddrive
# 1.CleanTheHD(['E:\\Music']) #Removes all playlist it findes in it's path;)
# Generating playlists on Harddrive
# 1.walkTheHD(['E:\\Music'],['mp3','avi','jpg','mpg','mov'])
# 2.walkTheHD(['E:\\Music','E:\\test.m3u'],['mp3','avi','jpg','mpg','mov']) #stores all playlistitems in one big file
# Generating playlists on Networkshare
# walkthesmb will be fixed to work with large lists.I will post fix in forum
# 1.walkTheSMB(['F\\musikk\\'],'computername', '10.0.0.6' , 'username ,'password',['mp3','avi','jpg','mpg','mov'])
#-------------------------------------------------------------------------
# Start using the walkcommands under here
#-------------------------------------------------------------------------
walkTheHD(['F:\\Music','Q:\\scripts\\playlistwalker\\playlistwalker.m3u'],['mp3','ogg','wav'])
playlist = xbmc.PlayList(0)
playlist.load("Q:\\scripts\\playlistwalker\\playlistwalker.m3u")
playlist.shuffle()
xbmc.Player().play(playlist)
Take it easy as usual kiddos.

<