4286
Comentário:
|
4955
Refactoring Wiki - eliminando pragma
|
Deleções são marcadas assim. | Adições são marcadas assim. |
Linha 1: | Linha 1: |
#pragma section-numbers off | |
Linha 4: | Linha 3: |
Esse foi meu primeiro script Python. A idéia é poder digitar {{{toca white stripes}}} na linha de comando do Linux ou !MiniCli, e o XMMS abriria com uma playlist com todos arquivos mp3 que tivessem essas palavras-chave. Também é possível usar esse script no Windows, basta mudar as variáveis {{{root_folder}}} e {{{player}}} apropriadamente (algo como {{{c:\\my documents\\mp3}}} e {{{c:\arquivos de programas\\winamp\\winamp.exe}}}, respectivamente). | Esse foi meu primeiro script Python. A idéia é poder digitar {{{toca white stripes}}} na linha de comando do Linux ou !MiniCli, e o XMMS abriria com uma playlist com todos arquivos mp3 que tivessem essas palavras-chave. Também é possível usar esse script no Windows, basta mudar as variáveis {{{root_folder}}} e {{{player}}} apropriadamente (algo como {{{"c:\\my documents\\mp3"}}} e {{{"c:\\arquivos de programas\\winamp\\winamp.exe"}}}, respectivamente). |
Linha 14: | Linha 13: |
Example: toca beatles let it be | |
Linha 15: | Linha 15: |
Searches all mp3 files with the _all_ specified keywords, generates a playlist and execute it. |
Searches all mp3 files with the _all_ specified keywords, generates a playlist and execute it. |
Linha 18: | Linha 18: |
It accepts the same options as winamp or xmms, such as -e to enqueue, and -s for shuffle. Actually the options are simply passed forward to the player so all the xmms/winamp options are available |
It accepts the same options as winamp or xmms, such as -e to enqueue, and -s for shuffle. Actually the options are simply passed forward to the player so all the xmms/winamp options are available. If you didn't do it already, don't forget to change the variable root_folder in this file (use any simple text editor). |
Linha 23: | Linha 26: |
# ------------ configuration options ------------ root_folder = "/windows/E/mp3" # change this to your # mp3 root folder... print "WARNING: root_folder not customized." # and remove this line. player = "xmms" # at windows might be something # like c:\\program files\\winamp\\winamp.exe playlist_filename = "playlist.m3u" # ------------ module imports ------------ |
|
Linha 27: | Linha 41: |
# -------- configuration options ------------ root_folder = "/windows/E/mp3" #change this to your mp3 root folder.... player = "xmms" #at windows might be something like c:\\program files\\winamp\\winamp.exe playlist_filename = "playlist.m3u" |
|
Linha 32: | Linha 42: |
def findFiles(directory,keylist): | # ------------ functions used ------------ def findFiles(directory, keylist): |
Linha 37: | Linha 49: |
Linha 39: | Linha 50: |
for (path,dname,fnames) in os.walk(directory): | for (path, dname, fnames) in os.walk(directory): |
Linha 41: | Linha 52: |
filename = string.lower(filename) #for each filename, check if it contains all the keywords for keyword in keylist: if not keyword in string.lower(filename): break else: #all keywords were found: add to the result list filenames.append(os.path.join(path, filename)) |
# for each filename, check if it contains all the keywords lowercase = string.lower(filename) if lowercase.endswith(".mp3"): for keyword in keylist: if not keyword in lowercase: break else: # all keywords were found: add to the result list filenames.append(os.path.join(path, filename)) |
Linha 51: | Linha 63: |
Linha 55: | Linha 68: |
playlist = open(playlist_filename,"w") #create the file playlist.write("#EXTM3U\n") #add the standard header |
playlist = open(playlist_filename, "w") #create the file playlist.write("#EXTM3U\n") #add the standard header |
Linha 58: | Linha 71: |
playlist.write(file + "\n") #add the items playlist.close |
playlist.write(file + "\n") #add the items playlist.close() |
Linha 61: | Linha 74: |
Linha 66: | Linha 80: |
command = player + " " + opt + " " + playlist_filename + " &" #print command | command = " ".join([player, opt, playlist_filename, "&"]) |
Linha 70: | Linha 83: |
if __name__ == "__main__": | def main(): """ Program main function. """ |
Linha 72: | Linha 89: |
if len(sys.argv) == 1: #if no keyword was entered, give the user a nice tip... print "Dude, you should enter a keyword to search the mp3's." print "Something like 'toca radiohead'" |
if len(sys.argv) == 1: # if no keyword was entered, print __doc__ # give the user a nice tip... |
Linha 76: | Linha 92: |
sys.argv = sys.argv[1:] #get any options (starting with '-') the user might have entered #these options will simply be passed forward to the player #one common option is -e to enqueue the songs instead of creating #a brand new playlist opt = [x for x in sys.argv if x[0] == "-"] |
args = sys.argv[1:] # get any options (starting with '-') the user might have # entered these options will simply be passed forward to # the player one common option is -e to enqueue the songs # instead of creating a brand new playlist opt = [x for x in args if x[0] == "-"] |
Linha 83: | Linha 100: |
#get the keywords to search for the mp3s keylist = [x for x in sys.argv if x not in opt] |
# get the keywords to search for the mp3s # if we don't use string.lower the user will never find # anything if it puts a uppercase letter in any of the # keywords. keylist = [string.lower(x) for x in args if x not in opt] |
Linha 86: | Linha 106: |
print "Looking for mp3 files with the keyword(s)..." print keylist files = findFiles(root_folder,keylist) |
print "Looking for mp3 files with the keyword(s): ", keylist files = findFiles(root_folder, keylist) |
Linha 90: | Linha 110: |
print "Finished! Found " + str(len(files)) + " file(s). So, let's play!" | print "Finished! Found", len(files), "file(s). So, let's play!" |
Linha 95: | Linha 116: |
print "-" * 69 | print "-" * 60 if __name__ == '__main__': main() |
Linha 100: | Linha 124: |
Renomeie o arquivo para {{{toca}}}, dê um {{{chmod +x toca}}} e copie para um diretório no seu {{{PATH}}}, por exemplo {{{/opt/kde3}}}. Então basta digitar {{{$ toca ''<nome da musica ou banda>''}}}. Pode usar quantas palavras quiser, para tornar a busca mais precisa (por exemplo, {{{toca beatles let it be}}}. Quaisquer opcões iniciadas com um "-" são passadas pro player, por exemplo "-e" para colocar as músicas na fila da playlist atual (enqueue) e "-s" para shuffle. | Renomeie o arquivo para {{{toca}}}, dê um {{{chmod +x toca}}} e copie para um diretório no seu {{{PATH}}}, por exemplo {{{/usr/local/bin/}}}. Então basta digitar {{{$ toca <palavras-chave>}}}. Pode usar quantas palavras quiser, para tornar a busca mais precisa (por exemplo, {{{toca beatles let it be}}}. Quaisquer opcões iniciadas com um "-" são passadas pro player, por exemplo "-e" para colocar as músicas na fila da playlist atual (enqueue) e "-s" para shuffle. |
Linha 103: | Linha 127: |
Procurar arquivos MP3 e gerar playlist
Esse foi meu primeiro script Python. A idéia é poder digitar toca white stripes na linha de comando do Linux ou MiniCli, e o XMMS abriria com uma playlist com todos arquivos mp3 que tivessem essas palavras-chave. Também é possível usar esse script no Windows, basta mudar as variáveis root_folder e player apropriadamente (algo como "c:\\my documents\\mp3" e "c:\\arquivos de programas\\winamp\\winamp.exe", respectivamente).
Boa sorte, e me contate caso tenha alguma dúvida. Também estou aberto a sugestões pra melhorar esse script. Ainda tem algumas coisas com cara de C e Java no código, mas aos poucos to me acostumando com o "estilo Python"
Código
""" Usage: toca <options> <keywords> .... Example: toca beatles let it be Searches all mp3 files with the _all_ specified keywords, generates a playlist and execute it. It accepts the same options as winamp or xmms, such as -e to enqueue, and -s for shuffle. Actually the options are simply passed forward to the player so all the xmms/winamp options are available. If you didn't do it already, don't forget to change the variable root_folder in this file (use any simple text editor). """ # ------------ configuration options ------------ root_folder = "/windows/E/mp3" # change this to your # mp3 root folder... print "WARNING: root_folder not customized." # and remove this line. player = "xmms" # at windows might be something # like c:\\program files\\winamp\\winamp.exe playlist_filename = "playlist.m3u" # ------------ module imports ------------ import sys import string import os # ------------ functions used ------------ def findFiles(directory, keylist): """ Gets a list of files in the directory (and subdirectories) with contains all the keywords in 'keylist' at the filename """ filenames = [] for (path, dname, fnames) in os.walk(directory): for filename in fnames: # for each filename, check if it contains all the keywords lowercase = string.lower(filename) if lowercase.endswith(".mp3"): for keyword in keylist: if not keyword in lowercase: break else: # all keywords were found: add to the result list filenames.append(os.path.join(path, filename)) return filenames def makePlaylist(fileList): """ Generates a playlist file for the filenames at fileList """ playlist = open(playlist_filename, "w") #create the file playlist.write("#EXTM3U\n") #add the standard header for file in fileList: playlist.write(file + "\n") #add the items playlist.close() def playIt(opt): """ Execute the playlist. """ opt = " ".join(opt) command = " ".join([player, opt, playlist_filename, "&"]) os.popen(command) def main(): """ Program main function. """ print "-" * 60 if len(sys.argv) == 1: # if no keyword was entered, print __doc__ # give the user a nice tip... else: args = sys.argv[1:] # get any options (starting with '-') the user might have # entered these options will simply be passed forward to # the player one common option is -e to enqueue the songs # instead of creating a brand new playlist opt = [x for x in args if x[0] == "-"] # get the keywords to search for the mp3s # if we don't use string.lower the user will never find # anything if it puts a uppercase letter in any of the # keywords. keylist = [string.lower(x) for x in args if x not in opt] print "Looking for mp3 files with the keyword(s): ", keylist files = findFiles(root_folder, keylist) if files: print "Finished! Found", len(files), "file(s). So, let's play!" makePlaylist(files) playIt(opt) else: print "Didn't find anything :-( Did you mispell it?" print "-" * 60 if __name__ == '__main__': main()
Para usar
Renomeie o arquivo para toca, dê um chmod +x toca e copie para um diretório no seu PATH, por exemplo /usr/local/bin/. Então basta digitar $ toca <palavras-chave>. Pode usar quantas palavras quiser, para tornar a busca mais precisa (por exemplo, toca beatles let it be. Quaisquer opcões iniciadas com um "-" são passadas pro player, por exemplo "-e" para colocar as músicas na fila da playlist atual (enqueue) e "-s" para shuffle.