gmyth-stream/server/0.2/lib/utils.py
author morphbr
Tue May 15 14:41:04 2007 +0100 (2007-05-15)
branchtrunk
changeset 651 76a3f315ef42
parent 585 a1783dab9ba6
child 653 3433df0d6ae3
permissions -rw-r--r--
[svn r657] * GMyth-Streamer
- Updated to get status (mencoder)
     1 #!/usr/bin/env
     2 
     3 __author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
     4 __author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
     5 __license__ = "GPL"
     6 __version__ = "0.3"
     7 
     8 import os
     9 import stat
    10 import sys
    11 import logging
    12 import urllib
    13 import gobject
    14 import imp
    15 
    16 log = logging.getLogger("gms.utils")
    17 
    18 __all__ = ("which", "load_plugins", "PluginSet", "getHTML")
    19 
    20 def which(app):
    21     """Function to implement which(1) unix command"""
    22     pl = os.environ["PATH"].split(os.pathsep)
    23     for p in pl:
    24         path = os.path.join(p, app)
    25         if os.path.isfile(path):
    26             st = os.stat(path)
    27             if st[stat.ST_MODE] & 0111:
    28                 return path
    29     return ""
    30 # which()
    31 
    32 
    33 def _load_module(pathlist, name):
    34     fp, path, desc = imp.find_module(name, pathlist)
    35     try:
    36         module = imp.load_module(name, fp, path, desc)
    37         return module
    38     finally:
    39         if fp:
    40             fp.close()
    41 # _load_module()
    42 
    43 
    44 class PluginSet(object):
    45     def __init__(self, basetype, *items):
    46         self.basetype = basetype
    47         self.map = {}
    48         self.list = []
    49 
    50         for i in items:
    51             self._add(i)
    52         self._sort()
    53     # __init__()
    54 
    55 
    56     def _add(self, item):
    57         self.map[item.name] = item
    58         self.list.append(item)
    59     # _add()
    60 
    61 
    62     def add(self, item):
    63         self._add()
    64         self._sort()
    65     # add()
    66 
    67 
    68     def __getitem__(self, spec):
    69         if isinstance(spec, basestring):
    70             return self.map[spec]
    71         else:
    72             return self.list[spec]
    73     # __getitem__()
    74 
    75 
    76     def get(self, name, default=None):
    77         return self.map.get(name, default)
    78     # get()
    79 
    80 
    81     def __iter__(self):
    82         return self.list.__iter__()
    83     # __iter__()
    84 
    85 
    86     def __len__(self):
    87         return len(self.list)
    88     # __len__()
    89 
    90 
    91     def _sort(self):
    92         self.list.sort(lambda a, b: cmp(a.priority, b.priority))
    93     # _sort()
    94 
    95 
    96     def update(self, pluginset):
    97         self.map.update(pluginset.map)
    98         self.list.extend(pluginset.list)
    99         self._sort()
   100     # update()
   101 
   102 
   103     def load_from_directory(self, directory):
   104         for i in load_plugins(directory, self.basetype):
   105             self._add(i)
   106         self._sort()
   107     # load_from_directory()
   108 
   109 
   110     def __str__(self):
   111         lst = []
   112         for o in self.list:
   113             lst.append('"%s" (%s)' % (o.name, o.__name__))
   114 
   115         return "%s(basetype=%s, items=[%s])" % \
   116                (self.__class__.__name__,
   117                 self.basetype.__name__,
   118                 ", ".join(lst))
   119     # __str__()
   120 # PluginSet
   121 
   122 
   123 def load_plugins(directory, basetype):
   124     """Function to load plugins from a given directory"""
   125     tn = basetype.__name__
   126     log.debug("Loading plugins from %s, type=%s" % (directory, tn))
   127 
   128 
   129     plugins = []
   130     for d in os.listdir(directory):
   131         if not d.endswith(".py"):
   132             continue
   133 
   134         name = d[0: -3]
   135         if name == "__init__":
   136             continue
   137 
   138         directory.replace(os.path.sep, ".")
   139         mod = _load_module([directory], name)
   140         for sym in dir(mod):
   141             cls = getattr(mod, sym)
   142             if isinstance(cls, type) and issubclass(cls, basetype) and \
   143                 cls != basetype:
   144                 plugins.append(cls)
   145                 log.info("Loaded %s (%s) from %s" % \
   146                          (cls.__name__, tn, os.path.join(directory, d)))
   147 
   148     return plugins
   149 # load_plugins()
   150 
   151 def getHTML(html_file, params={}):
   152     """This function parses a file 'html_file.html' with the given
   153     parameters and returns a formated web-page"""
   154     try:
   155         filename = os.path.join(sys.path[0], "html", html_file + ".html")
   156         html = open(filename).read() % params
   157         return html
   158     except Exception, e:
   159         return "HTML format error. Wrong keys: %s" % e
   160 
   161 # getHTML
   162 
   163 def progress_bar(log, value, max, barsize):
   164    chars = int(value * barsize / float(max))
   165    percent = int((value / float(max)) * 100)
   166    sys.stdout.write("#" * chars)
   167    sys.stdout.write(" " * (barsize - chars + 2))
   168    if value >= max:
   169       sys.stdout.write("done. \n\n")
   170    else:
   171       sys.stdout.write("[%3i%%]\r" % (percent))
   172       sys.stdout.flush()
   173 
   174 # progress_bar by osantana