当前位置: 首页>>代码示例>>Python>>正文


Python progressbar.Timer方法代码示例

本文整理汇总了Python中progressbar.Timer方法的典型用法代码示例。如果您正苦于以下问题:Python progressbar.Timer方法的具体用法?Python progressbar.Timer怎么用?Python progressbar.Timer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在progressbar的用法示例。


在下文中一共展示了progressbar.Timer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: show_progress

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def show_progress(block_num, block_size, total_size):
    global pbar

    if pbar is None:
        if total_size > 0:
            prefixes = ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')
            power = min(int(math.log(total_size, 2) / 10), len(prefixes) - 1)
            scaled = float(total_size) / (2 ** (10 * power))
            total_size_str = '{:.1f} {}B'.format(scaled, prefixes[power])
            try:
                marker = '█'
            except UnicodeEncodeError:
                marker = '*'
            widgets = [
                progressbar.Percentage(),
                ' ', progressbar.DataSize(),
                ' / ', total_size_str,
                ' ', progressbar.Bar(marker=marker),
                ' ', progressbar.ETA(),
                ' ', progressbar.AdaptiveTransferSpeed(),
            ]
            pbar = progressbar.ProgressBar(widgets=widgets,
                                           max_value=total_size)
        else:
            widgets = [
                progressbar.DataSize(),
                ' ', progressbar.Bar(marker=progressbar.RotatingMarker()),
                ' ', progressbar.Timer(),
                ' ', progressbar.AdaptiveTransferSpeed(),
            ]
            pbar = progressbar.ProgressBar(widgets=widgets,
                                           max_value=progressbar.UnknownLength)

    downloaded = block_num * block_size
    if downloaded < total_size:
        pbar.update(downloaded)
    else:
        pbar.finish()
        pbar = None 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:41,代码来源:dataset.py

示例2: reset

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def reset(self, mode, make_pbar=True, string=''):
        self.mode = mode
        self.u = 0

        if make_pbar:
            widgets = [string, Timer(), ' | ',
                       Percentage(), ' | ', ETA(), Bar()]
            if len([len(loader[self.mode]) for loader
                    in self.loaders.values()]) == 0:
                maxval = 1000
            else:
                maxval = min(len(loader[self.mode])
                             for loader in self.loaders.values())
            self.pbar = ProgressBar(widgets=widgets, maxval=maxval).start()
        else:
            self.pbar = None

        sources = self.loaders.keys()
        self.iterators = dict((source, self.make_iterator(source))
                              for source in sources) 
开发者ID:rdevon,项目名称:cortex,代码行数:22,代码来源:data_handler.py

示例3: deleteHostsByHostgroup

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def deleteHostsByHostgroup(groupname):
    hostgroup = zapi.hostgroup.get(output=['groupid'],filter={'name': groupname})
    if hostgroup.__len__() != 1:
        logger.error('Hostgroup not found: %s\n\tFound this: %s' % (groupname,hostgroup))
    groupid = int(hostgroup[0]['groupid'])
    hosts = zapi.host.get(output=['name','hostid'],groupids=groupid)
    total = len(hosts)
    logger.info('Hosts found: %d' % (total))
    if ( args.run ):
        x = 0
        bar = ProgressBar(maxval=total,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
        logger.echo = False
        for host in hosts:
            x = x + 1
            bar.update(x)
            logger.debug('(%d/%d) >> Removing >> %s' % (x, total, host))
            out = zapi.globo.deleteMonitors(host['name'])
        bar.finish()
        logger.echo = True
    else:
        logger.info('No host removed due to --no-run arg. Full list of hosts:')
        for host in hosts:
            logger.info('%s' % host['name'])
    return 
开发者ID:globocom,项目名称:zabbix-scripts,代码行数:26,代码来源:zbx_deleteMonitors.py

示例4: hosts_disable_all

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def hosts_disable_all():
  """
  status de host 0 = enabled
  status de host 1 = disabled
  """
  logger.info('Disabling all hosts, in blocks of 1000')
  hosts = zapi.host.get(output=[ 'hostid' ], search={ 'status': 0 })
  maxval = int(ceil(hosts.__len__())/1000+1)
  bar = ProgressBar(maxval=maxval,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
  i = 0
  for i in xrange(maxval):
    block = hosts[:1000]
    del hosts[:1000]
    result = zapi.host.massupdate(hosts=[ x for x in block ], status=1)
    i += 1
    bar.update(i)
  bar.finish()
  logger.info('Done')
  return 
开发者ID:globocom,项目名称:zabbix-scripts,代码行数:21,代码来源:zbx_clone.py

示例5: proxy_passive_to_active

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def proxy_passive_to_active():
  """
  status de prxy 5 = active
  status de prxy 6 = passive
  """
  logger.info('Change all proxys to active')
  proxys = zapi.proxy.get(output=[ 'shorten', 'host' ],
    filter={ 'status': 6 })
  if ( proxys.__len__() == 0 ):
    logger.info('Done')
    return
  bar = ProgressBar(maxval=proxys.__len__(),widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
  i = 0
  for x in proxys:
    i += 1
    proxyid = x['proxyid']
    result = zapi.proxy.update(proxyid=proxyid, status=5)
    logger.echo = False
    logger.debug('Changed from passive to active proxy: %s' % (x['host']))
    bar.update(i)
  bar.finish()
  logger.echo = True
  logger.info('Done')
  return 
开发者ID:globocom,项目名称:zabbix-scripts,代码行数:26,代码来源:zbx_clone.py

示例6: create_bar

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def create_bar(self):
        """Create a new progress bar.

        Calls `self.get_iter_per_epoch()`, selects an appropriate
        set of widgets and creates a ProgressBar.

        """
        iter_per_epoch = self.get_iter_per_epoch()
        epochs_done = self.main_loop.log.status['epochs_done']

        if iter_per_epoch is None:
            widgets = ["Epoch {}, step ".format(epochs_done),
                       progressbar.Counter(), ' ',
                       progressbar.BouncingBar(), ' ',
                       progressbar.Timer()]
            iter_per_epoch = progressbar.UnknownLength
        else:
            widgets = ["Epoch {}, step ".format(epochs_done),
                       progressbar.Counter(),
                       ' (', progressbar.Percentage(), ') ',
                       progressbar.Bar(), ' ',
                       progressbar.Timer(), ' ', progressbar.ETA()]

        return progressbar.ProgressBar(widgets=widgets,
                                       max_value=iter_per_epoch) 
开发者ID:rizar,项目名称:attention-lvcsr,代码行数:27,代码来源:__init__.py

示例7: set_tot_elaborations

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def set_tot_elaborations(self, tot_elaborations):
        """
        Set the total number of elaborations

        :param tot_elaborations: total number of elaborations
        :return: None
        """

        widgets = [
            progressbar.Percentage(),
            ' (', progressbar.SimpleProgress(), ') ',

            progressbar.Bar(),
            progressbar.Timer(),
            ' ETC: ', self._ETC, ' '
        ]
        self._bar = progressbar.ProgressBar(redirect_stderr=True, max_value=tot_elaborations, widgets=widgets)
        self._bar.start()
        self._tot_elaborations = tot_elaborations 
开发者ID:ucsb-seclab,项目名称:karonte,代码行数:21,代码来源:bar_logger.py

示例8: run

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def run(self):
        try:
            from progressbar import ProgressBar, Bar, Counter, Timer, ETA, Percentage, RotatingMarker
            widgets = [Percentage(), Bar(left='[', right=']'), ' Processed: ', Counter(), '/', "%s" % self.task_count, ' total files (', Timer(), ') ', ETA()]
            pb = ProgressBar(widgets=widgets, maxval=self.task_count).start()
            while self.task_queue.qsize():
                pb.update(self.task_count - self.task_queue.qsize())
                
                time.sleep(0.5)
            pb.finish()
        except KeyboardInterrupt:
            warning("progressbar interrupted by user\n")
            return 1
        except ImportError:
            warning("progressbar module not available")
        except:
            warning("unknown error from progress bar")

        return 0 
开发者ID:lmco,项目名称:laikaboss,代码行数:21,代码来源:laika.py

示例9: progress_bar

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def progress_bar(event):
    if event == 'Checking' or event == 'Calculating':
        widgets = [progressbar.AnimatedMarker(), ' ', event + ' (Queue: ', progressbar.Counter(), ') ', progressbar.Timer()]
        bar = progressbar.ProgressBar(widgets=widgets, max_value=progressbar.UnknownLength)
    else:
        widgets = [event + ' ', progressbar.Bar(), progressbar.Percentage(),
            ' (', progressbar.Timer(), ', ', progressbar.ETA(), ')']
        bar = progressbar.ProgressBar(widgets=widgets, max_value=100)
    return bar 
开发者ID:shirosaidev,项目名称:diskover,代码行数:11,代码来源:diskover.py

示例10: capture_on_interface

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def capture_on_interface(interface, name, timeout=60):
    """
    :param interface: The name of the interface on which to capture traffic
    :param name: The name of the capture file
    :param timeout: A limit in seconds specifying how long to capture traffic
    """

    if timeout < 15:
        logger.error("Timeout must be over 15 seconds.")
        return
    if not sys.warnoptions:
        warnings.simplefilter("ignore")
    start = time.time()
    widgets = [
        progressbar.Bar(marker=progressbar.RotatingMarker()),
        ' ',
        progressbar.FormatLabel('Packets Captured: %(value)d'),
        ' ',
        progressbar.Timer(),
    ]
    progress = progressbar.ProgressBar(widgets=widgets)
    capture = pyshark.LiveCapture(interface=interface, output_file=os.path.join('tmp', name))
    pcap_size = 0
    for i, packet in enumerate(capture.sniff_continuously()):
        progress.update(i)
        if os.path.getsize(os.path.join('tmp', name)) != pcap_size:
            pcap_size = os.path.getsize(os.path.join('tmp', name))
        if not isinstance(packet, pyshark.packet.packet.Packet):
            continue
        if time.time() - start > timeout:
            break
        if pcap_size > const.PT_MAX_BYTES:
            break
    capture.clear()
    capture.close()
    return pcap_size 
开发者ID:PacketTotal,项目名称:HoneyBot,代码行数:38,代码来源:utils.py

示例11: __init__

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def __init__(self, steps_nb, step_name_len):
    """
    Constructor
    """
    threading.Thread.__init__(self)
    self._running = False
    self._current_step = 0
    self._steps_nb = steps_nb
    self._step_name_len = step_name_len + len(str(steps_nb)) * 2 + 2
    self._widgets = [" ".ljust(self._step_name_len),
                     ' [', progressbar.Timer(), '] ',
                     progressbar.Bar(),
                     ' (', progressbar.ETA(), ') ',
                    ]
    self._pbar = progressbar.ProgressBar(max_value=steps_nb, widgets=self._widgets) 
开发者ID:aacebedo,项目名称:i3-xfce,代码行数:17,代码来源:core.py

示例12: createSQL

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def createSQL(table,values,name='insert'):
	'''
	Generate the SQL insert line, breaking each insert to up to ~1k values
	and up to ~1k insert's (~1M values total for each SQL file)
	'''
	logger.info('Generating SQL file')
	queryInsert='INSERT INTO %s (itemid,clock,num,value_min,value_avg,value_max) VALUES' % table
	i=0 # Controls the progress bar
	x=0 # Controls number of inserts in one line
	y=0 # Controls number of lines in one file
	z=0 # Controls number of file name
	valuesLen=values.__len__()
	sqlFile='%s.sql.%d' % (name,z)
	logger.debug('Total itens for %s: %d' % (name,valuesLen))

	if valuesLen > 0:
		bar=ProgressBar(maxval=valuesLen,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
		for value in values:
			i+=1
			x+=1
			if x != 1: # First line only
				sqlInsert='%s,%s' % (sqlInsert,value)
			else:
				sqlInsert=value
			if y >= 1000: # If there is more than 1k lines, write to new file
				z+=1
				y=0
			if x >= 1000 or i == valuesLen: # If there is more than 1k values or we finished our list, write to file
				sqlFile='%s.sql.%d' % (name,z)
				fileAppend(f=sqlFile,content='%s %s;\n' % (queryInsert,sqlInsert))
				x=0
				y+=1
				sqlInsert=''
			if args.loglevel.upper() != 'DEBUG': # Dont print progressbar if in debug mode
				bar.update(i)
		bar.finish()
	else:
		logger.warning('No values received') 
开发者ID:globocom,项目名称:zabbix-scripts,代码行数:40,代码来源:move_items.py

示例13: discovery_disable_all

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def discovery_disable_all(status=0):
  """
  Alterar status de todos os discoveries *auto*
  Status 0 = enable
  Status 1 = disable
  """ 
  logger.info('Disabling all network discoveries')
  druleids = zapi.drule.get(output=[ 'druleid', 'iprange', 'name', 'proxy_hostid', 'status' ],
      selectDChecks='extend', filter={ 'status': 0 })
  if ( druleids.__len__() == 0 ):
    logger.info('Done')
    return
  bar = ProgressBar(maxval=druleids.__len__(),widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
  i = 0
  for x in druleids:
    params_disable = {
      'druleid': x['druleid'],
      'iprange': x['iprange'],
      'name': x['name'],
      'dchecks': x['dchecks'],
      'status': 1
    }
    out = zapi.drule.update(**params_disable)
    logger.echo = False
    if out:
      logger.debug('\tNew status: %s (%s) --> %d' % (x['name'],out['druleids'],status))
    else:
      logger.warning('\tFAILED to change status: %s (%s) --> %d' % (x['name'],out['druleids'],status))
    i += 1
    bar.update(i)
  logger.echo = True
  bar.finish()
  logger.info('Done')
  return 
开发者ID:globocom,项目名称:zabbix-scripts,代码行数:36,代码来源:zbx_clone.py

示例14: compute_ranks

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def compute_ranks(scoring_function, triples, entity_set, true_triples=None):
    subject_ranks, object_ranks = [], []
    subject_ranks_filtered, object_ranks_filtered = [], []

    bar = progressbar.ProgressBar(
        max_value=len(triples),
        widgets=[' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '])
    for s, p, o in bar(triples):
        subject_triples = [(s, p, o)] + [(x, p, o) for x in entity_set if x != s]
        object_triples = [(s, p, o)] + [(s, p, x) for x in entity_set if x != o]

        subject_triple_scores = np.array(scoring_function(subject_triples))
        object_triple_scores = np.array(scoring_function(object_triples))

        subject_rank = 1 + np.argsort(np.argsort(- subject_triple_scores))[0]
        object_rank = 1 + np.argsort(np.argsort(- object_triple_scores))[0]

        subject_ranks.append(subject_rank)
        object_ranks.append(object_rank)

        if true_triples is None:
            true_triples = []

        for idx, triple in enumerate(subject_triples):
            if triple != (s, p, o) and triple in true_triples:
                subject_triple_scores[idx] = - np.inf

        for idx, triple in enumerate(object_triples):
            if triple != (s, p, o) and triple in true_triples:
                object_triple_scores[idx] = - np.inf

        subject_rank_filtered = 1 + np.argsort(np.argsort(- subject_triple_scores))[0]
        object_rank_filtered = 1 + np.argsort(np.argsort(- object_triple_scores))[0]

        subject_ranks_filtered.append(subject_rank_filtered)
        object_ranks_filtered.append(object_rank_filtered)

    return (subject_ranks, object_ranks), (subject_ranks_filtered, object_ranks_filtered) 
开发者ID:uclnlp,项目名称:jack,代码行数:40,代码来源:link_prediction.py

示例15: __call__

# 需要导入模块: import progressbar [as 别名]
# 或者: from progressbar import Timer [as 别名]
def __call__(self, epoch):
        if self._batches is None:
            logger.info("Preparing evaluation data...")
            self._batches = self.reader.input_module.batch_generator(self._dataset, self._batch_size, is_eval=True)

        logger.info("Started evaluation %s" % self._info)
        metrics = defaultdict(lambda: list())
        bar = progressbar.ProgressBar(
            max_value=len(self._dataset) // self._batch_size + 1,
            widgets=[' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') '])
        for i, batch in bar(enumerate(self._batches)):
            inputs = self._dataset[i * self._batch_size:(i + 1) * self._batch_size]
            predictions = self.reader.model_module(batch, self._ports)
            m = self.apply_metrics(inputs, predictions)
            for k in self._metrics:
                metrics[k].append(m[k])

        metrics = self.combine_metrics(metrics)
        super().add_to_history(metrics, self._iter, epoch)

        printmetrics = sorted(metrics.keys())
        res = "Epoch %d\tIter %d\ttotal %d" % (epoch, self._iter, self._total)
        for m in printmetrics:
            res += '\t%s: %.3f' % (m, metrics[m])
            self.update_summary(self._iter, self._info + '_' + m, metrics[m])
            if self._write_metrics_to is not None:
                with open(self._write_metrics_to, 'a') as f:
                    f.write("{0} {1} {2:.5}\n".format(datetime.now(), self._info + '_' + m,
                                                      np.round(metrics[m], 5)))
        res += '\t' + self._info
        logger.info(res)

        if self._side_effect is not None:
            self._side_effect_state = self._side_effect(metrics, self._side_effect_state) 
开发者ID:uclnlp,项目名称:jack,代码行数:36,代码来源:hooks.py


注:本文中的progressbar.Timer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。