Ubuntu na terra do pão di queijo

26/09/2008

Scripts que facilitam a vida![1].script

Filed under: Diversos,Multimedia,Software Livre — Leonardo Amaral @ 20:00

Eis os scripts. Lembrando que o primeiro tem que ser salvo como progressbar.py no local que seu script estiver ou aonde o python consiga localizar. Para salva-los, clique em “view plain”, selecione todo o texto, cole no seu editor favorito e cole. Vou enviar um tar.gz também em breve Baixe AQUI.

#!/usr/bin/python  
# -*- coding: iso-8859-1 -*-  
#  
# progressbar – Text progressbar library for python.  
# Copyright (c) 2005 Nilton Volpato  
#  
# This library is free software; you can redistribute it and/or  
# modify it under the terms of the GNU Lesser General Public  
# License as published by the Free Software Foundation; either  
# version 2.1 of the License, or (at your option) any later version.
#  
# This library is distributed in the hope that it will be useful,  
# but WITHOUT ANY WARRANTY; without even the implied warranty of  
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.  
#  
# You should have received a copy of the GNU Lesser General Public  
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

“””Text progressbar library for python.

This library provides a text mode progressbar. This is tipically used
to display the progress of a long running operation, providing a  
visual clue that processing is underway.  

The ProgressBar class manages the progress, and the format of the line
is given by a number of widgets. A widget is an object that may  
display diferently depending on the state of the progress. There are  
three types of widget:  
– a string, which always shows itself;  
– a ProgressBarWidget, which may return a diferent value every time  
it’s update method is called; and  
– a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it
expands to fill the remaining width of the line.  

The progressbar module is very easy to use, yet very powerful. And
automatically supports features like auto-resizing when available.
“””  

__author__ = “Nilton Volpato”
__author_email__ = “first-name dot last-name @ gmail.com”
__date__ = “2006-05-07”  
__version__ = “2.2”  

# Changelog
#  
# 2006-05-07: v2.2 fixed bug in windows
# 2005-12-04: v2.1 autodetect terminal width, added start method
# 2005-12-04: v2.0 everything is now a widget (wow!)  
# 2005-12-03: v1.0 rewrite using widgets  
# 2005-06-02: v0.5 rewrite  
# 2004-??-??: v0.1 first version  

import sys, time
from array import array
try:  
  from fcntl import ioctl
  import termios  
except ImportError:  
  pass  
import signal  

class ProgressBarWidget(object):
  “””This is an element of ProgressBar formatting.

  The ProgressBar object will call it’s update value when an update
  is needed. It’s size may change between call, but the results will
  not be good if the size changes drastically and repeatedly.  
  “””  
  def update(self, pbar):  
  “””Returns the string representing the widget.  

  The parameter pbar is a reference to the calling ProgressBar,
  where one can access attributes of the class for knowing how
  the update must be made.  

  At least this function must be overriden.”””
  pass  

class ProgressBarWidgetHFill(object):
  “””This is a variable width element of ProgressBar formatting.

  The ProgressBar object will call it’s update value, informing the
  width this object must the made. This is like TeX \hfill, it will
  expand to fill the line. You can use more than one in the same  
  line, and they will all have the same width, and together will  
  fill the line.  
  “””  
  def update(self, pbar, width):  
  “””Returns the string representing the widget.  

  The parameter pbar is a reference to the calling ProgressBar,
  where one can access attributes of the class for knowing how
  the update must be made. The parameter width is the total  
  horizontal width the widget must have.  

  At least this function must be overriden.”””
  pass  

class ETA(ProgressBarWidget):
  “Widget for the Estimated Time of Arrival”
  def format_time(self, seconds):  
  return time.strftime(‘%H:%M:%S’, time.gmtime(seconds))
  def update(self, pbar):  
  if pbar.currval == 0:  
  return ‘ETA: –:–:–‘  
  elif pbar.finished:  
  return ‘Time: %s’ % self.format_time(pbar.seconds_elapsed)
  else:  
  elapsed = pbar.seconds_elapsed  
  eta = elapsed * pbar.maxval / pbar.currval – elapsed  
  return ‘ETA: %s’ % self.format_time(eta)  

class FileTransferSpeed(ProgressBarWidget):
  “Widget for showing the transfer speed (useful for file transfers).”
  def __init__(self):  
  self.fmt = ‘%6.2f %s’  
  self.units = [‘B’,’K’,’M’,’G’,’T’,’P’]  
  def update(self, pbar):  
  if pbar.seconds_elapsed < 2e-6:#== 0:     bps = 0.0     else:     bps = float(pbar.currval) / pbar.seconds_elapsed     spd = bps     for u in self.units:     if spd >> pbar = ProgressBar().start()
  >>> for i in xrange(100):  
  … # do something  
  … pbar.update(i+1)  
  …  
  >>> pbar.finish()  

  But anything you want to do is possible (well, almost anything).
  You can supply different widgets of any type in any order. And you
  can even write your own widgets! There are many widgets already  
  shipped and you should experiment with them.  

  When implementing a widget update method you may access any
  attribute or function of the ProgressBar object calling the
  widget’s update method. The most important attributes you would
  like to access are:  
  – currval: current value of the progress, 0 <= currval 0     self.maxval = maxval     self.widgets = widgets     self.fd = fd     self.signal_set = False     if term_width is None:     try:     self.handle_resize(None,None)     signal.signal(signal.SIGWINCH, self.handle_resize)     self.signal_set = True     except:     self.term_width = 79     else:     self.term_width = term_width     self.currval = 0   self.finished = False   self.prev_percentage = -1   self.start_time = None     self.seconds_elapsed = 0   def handle_resize(self, signum, frame):   h,w=array('h', ioctl(self.fd,termios.TIOCGWINSZ,''*8))[:2]   self.term_width = w     def percentage(self):   "Returns the percentage of the progress."   return self.currval*100.0 / self.maxval     def _format_widgets(self):   r = []     hfill_inds = []     num_hfill = 0     currwidth = 0     for i, w in enumerate(self.widgets):   if isinstance(w, ProgressBarWidgetHFill):   r.append(w)     hfill_inds.append(i)     num_hfill += 1     elif isinstance(w, (str, unicode)):     r.append(w)     currwidth += len(w)     else:     weval = w.update(self)     currwidth += len(weval)     r.append(weval)     for iw in hfill_inds:     r[iw] = r[iw].update(self, (self.term_width-currwidth)/num_hfill)   return r     def _format_line(self):   return ''.join(self._format_widgets()).ljust(self.term_width)   def _need_update(self):   return int(self.percentage()) != int(self.prev_percentage)   def update(self, value):   "Updates the progress bar to a new value."   assert 0 <= value >> pbar = ProgressBar().start()  
  >>> for i in xrange(100):  
  … # do something  
  … pbar.update(i+1)  
  …  
  >>> pbar.finish()  
  “””  
  self.update(0)  
  return self  

  def finish(self):
  “””Used to tell the progress is finished.”””
  self.update(self.maxval)  
  if self.signal_set:  
  signal.signal(signal.SIGWINCH, signal.SIG_DFL)

if __name__==’__main__’:
  import os  

  def example1():
  widgets = [‘Test: ‘, Percentage(), ‘ ‘, Bar(marker=RotatingMarker()),
  ‘ ‘, ETA(), ‘ ‘, FileTransferSpeed()]  
  pbar = ProgressBar(widgets=widgets, maxval=10000000).start()  
  for i in range(1000000):  
  # do something  
  pbar.update(10*i+1)  
  pbar.finish()  
  print  

  def example2():
  class CrazyFileTransferSpeed(FileTransferSpeed):
  “It’s bigger between 45 and 80 percent”  
  def update(self, pbar):  
  if 45 < pbar.percentage() < 80:     return 'Bigger Now ' + FileTransferSpeed.update(self,pbar)   else:     return FileTransferSpeed.update(self,pbar)     widgets = [CrazyFileTransferSpeed(),' <<>> ‘, Percentage(),’ ‘, ETA()]
  pbar = ProgressBar(widgets=widgets, maxval=10000000)  
  # maybe do something  
  pbar.start()  
  for i in range(2000000):  
  # do something  
  pbar.update(5*i+1)  
  pbar.finish()
  print

  def example3():
  widgets = [Bar(‘>’), ‘ ‘, ETA(), ‘ ‘, ReverseBar(‘<')]   pbar = ProgressBar(widgets=widgets, maxval=10000000).start()   for i in range(1000000):   # do something   pbar.update(10*i+1)   pbar.finish()   print   def example4():   widgets = ['Test: ', Percentage(), ' ',   Bar(marker='0',left='[',right=']'),   ' ', ETA(), ' ', FileTransferSpeed()]   pbar = ProgressBar(widgets=widgets, maxval=500)   pbar.start()   for i in range(100,500+1,50):   time.sleep(0.2)   pbar.update(i)   pbar.finish()   print   example1()   example2()   example3()   example4() [/sourcecode] [sourcecode language='python'] #!/usr/bin/python # -*- coding: utf8 -*- """   A Aplication to create MP4 files for Cellphones   Copyright (C) 2008 Leonardo Silva Amaral   Copyright (C) 2008 Clovis Fabricio Costa   This program is free software; you can redistribute it and/or modify   it under the terms of the GNU General Public License version 2 as published by   the Free Software Foundation.   This program is distributed in the hope that it will be useful,   but WITHOUT ANY WARRANTY; without even the implied warranty of   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the   GNU General Public License for more details.   You should have received a copy of the GNU General Public License   along with this program; if not, write to the Free Software   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import sys import re import optparse import progressbar import subprocess import tempfile VERSION='0.0.1a1' class OptionRequired(Exception): pass def read_line(fileobj, terminator='r'):   """   Generator to read a file up to a terminator and yield the buffer   """   buff = []   for char in iter(lambda: fileobj.read(1), ''):   if char == terminator:   yield ''.join(buff)   buff = []   else:   buff.append(char)   if buff:   yield ''.join(buff) class Application(object):   def __init__(self):   # Init options:   parser = optparse.OptionParser(usage="%prog [options]",   version="%prog " + VERSION)   parser.set_defaults(font_path='/usr/share/fonts/truetype/msttcorefonts/',   font='impact.ttf',   mencoder_path='mencoder')   parser.add_option("-i", "--input", dest="input",   help="seleciona o arquivo de origem")   parser.add_option("-o", "--output", dest="output",   help="seleciona o arquivo de destino")   parser.add_option("-s", "--sub", dest="subtitle",   help="Code file with specified subtitles")   parser.add_option("-p", "--font_path", dest="font_path",   help="Path to the system font directory")   parser.add_option("-f", "--font", dest="font",   help="Font to use when using subtitles. Default: %default")   parser.add_option("-m", "--mencoder", dest="mencoder_path",   help="mencoder path")   self.opt, extra_args = parser.parse_args()   # Check for required options   for required in 'input', 'output':   if getattr(self.opt, required, None) is None:   raise OptionRequired('Option %s is required' % required)   def __call__(self):   """Performs the conversion"""   self.pbar = self._create_pb('Convertendo arquivo... ')   if self.opt.subtitle:   subcmd = ['-sub', self.opt.subtitle, '-font',   repr(os.path.join(self.opt.font_path, self.opt.font)),   '-ffactor', '1', '-sub-bg-alpha', '0', '-sub-bg-color',   '0', '-spualign', '-1', '-subalign', '2', '-subfont-autoscale',   '2', '-subpos', '95', '-subfont-text-scale', '4', '-utf8']   else:   subcmd = []   tmpfile = tempfile.mktemp('.log', 'mencoder_divx2pass_')   #---First pass---   cmd = [self.opt.mencoder_path, self.opt.input, '-nosound']   cmd.extend(subcmd)   cmd.extend(['-of', 'lavf', '-lavfopts', 'format=mp4', '-ovc',   'lavc', '-passlogfile', tmpfile, '-lavcopts',   'vglobal=1:vcodec=mpeg4:keyint=25:vbitrate=280:vpass=1',   '-vf', 'scale=220:-3,expand=220:176,harddup,pp=ac', '-o',   '/dev/null'])   #print "DEBUG: running", ' '.join(cmd)   self._run_command(cmd, 0)   #---Second pass---   cmd = [self.opt.mencoder_path, self.opt.input]   cmd.extend(subcmd)   cmd.extend(['-of', 'lavf', '-lavfopts', 'format=mp4', '-oac', 'lavc',   '-passlogfile', tmpfile, '-ovc', 'lavc', '-lavcopts',   'aglobal=1:vglobal=1:acodec=libfaac:abitrate=128:' +   'vcodec=mpeg4:keyint=25:vbitrate=280:vpass=2', '-vf',   'scale=220:-3,expand=220:176,harddup,pp=ac',   '-o', self.opt.output])   #print "DEBUG: running", ' '.join(cmd)   self._run_command(cmd, 1)   # removes temp file:   os.remove(tmpfile)   self.pbar.finish()   def _run_command(self, command, progress):   process = subprocess.Popen(command, stdout=subprocess.PIPE,   stderr=open(os.devnull, 'r+w'))   for line in read_line(process.stdout):   # parse percentage:   paren = re.search('((d+)D*?)', line)   if paren and re.match('^Pos:*', line):   percentage = int(paren.group(1))   self.pbar.update(progress * 100 + percentage)   def _create_pb(self, msg, maxval=200): widgets = [msg, progressbar.Percentage(), ' ', progressbar.Bar(marker=progressbar.RotatingMarker()), ' ', progressbar.ETA()]   return progressbar.ProgressBar(widgets=widgets, maxval=maxval) if __name__ == "__main__":   try:   app = Application()   app()   except OptionRequired, e:   print e   sys.exit(1)   except OSError:   print u"mencoder não encontrado. Por favor instale o mencoder ou passe -m"   sys.exit(2) [/sourcecode]

Anúncios

4 Comentários »

  1. […] resolvi portar meu código pra Python. Com a ajuda do nosklo o script ficou bem legal. Eles estão aqui (Eles é porque tem o progressbar.py para fazer a barra de progresso). Não inclui este post […]

    Pingback por Scripts que facilitam a vida![1] « Ubuntu na terra do pão di queijo — 26/09/2008 @ 20:08 | Responder

  2. vc tem algum script pra enviar arquivos por bluetooth pro meu cel usando o obex-data-server ? por opp nao por ftp

    Comentário por xtecox — 13/11/2008 @ 23:47 | Responder

  3. xtecox: Enviar via obex eu nunca fiz, mas não parece ser dificil não. Me contacte denovo no fim de semana que eu vejo se faço. :]

    Comentário por Leonardo Amaral — 14/11/2008 @ 6:13 | Responder

  4. vlws ! eu to no #ubuntu-br mas soh respondo a noite

    Comentário por xtecox — 14/11/2008 @ 8:31 | Responder


RSS feed for comments on this post. TrackBack URI

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

Blog no WordPress.com.

%d blogueiros gostam disto: