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


Python progress.Bar方法代码示例

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


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

示例1: _eraseSectors

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def _eraseSectors(self, offset, length, tries=3):
        """Clears one or more sectors"""
        assert offset % self.sector_size == 0
        sectors_offset = offset // self.sector_size

        assert length % self.sector_size == 0
        sector_count = length // self.sector_size

        with progress.Bar(expected_size=sector_count) as bar:
            for sector in range(sector_count):
                sector_index = sectors_offset + sector

                bar.show(sector)

                # Erase sector up to 'tries' times
                for _ in range(tries):
                    if self._eraseSector(sector_index):
                        break
                else:  # No erase was successful
                    logError('Could not erase sector %08x' % sector_index)
                    return False

            bar.show(sector_count)

        return True 
开发者ID:nfd,项目名称:spi-flash-programmer,代码行数:27,代码来源:spi_flash_programmer_client.py

示例2: readToFile

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def readToFile(self, filename, flash_offset=0, length=DEFAULT_FLASH_SIZE):
        """Read the data from the flash into the file"""
        if length % self.page_size != 0:
            logError('length must be a multiple of the page size %d' % self.page_size)
            return False

        if flash_offset % self.page_size != 0:
            logError('flash_offset must be a multiple of the page size %d' % self.page_size)
            return False

        page_count = length // self.page_size
        pages_offset = flash_offset // self.page_size

        try:
            with open(filename, 'wb') as file:
                with progress.Bar(expected_size=page_count) as bar:
                    for page in range(page_count):
                        bar.show(page)

                        page_index = pages_offset + page
                        data = self._readPage(page_index)
                        if data is not None:
                            file.write(data)
                            continue

                        # Invalid data
                        logError('Could not read page 0x%08x' % page_index)
                        return True

                    bar.show(page_count)

            logOk('Done')
            return True
        except IOError:
            logError('Could not write to file \'%s\'' % filename)
            return True 
开发者ID:nfd,项目名称:spi-flash-programmer,代码行数:38,代码来源:spi_flash_programmer_client.py

示例3: __init__

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def __init__(self, data: memoryview, logger: logging.Logger):
            self._file = io.BytesIO(data)
            self._size = len(data)
            self._enabled = logger.isEnabledFor(logging.INFO)
            if self._enabled:
                self._progress = progress.Bar(expected_size=self._size)
            else:
                logger.debug("Progress indication is not enabled") 
开发者ID:src-d,项目名称:modelforge,代码行数:10,代码来源:gcs_backend.py

示例4: create_progress_callback

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def create_progress_callback(encoder):
    encoder_len = encoder.len
    bar = ProgressBar(expected_size=encoder_len, filled_char='=')

    def callback(monitor):
        bar.show(monitor.bytes_read)
    return callback 
开发者ID:floydhub,项目名称:floyd-cli,代码行数:9,代码来源:data.py

示例5: create_progress_callback

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def create_progress_callback(encoder):
    encoder_len = encoder.len
    bar = ProgressBar(expected_size=encoder_len, filled_char='=')

    def callback(monitor):
        bar.show(monitor.bytes_read)

    return callback, bar 
开发者ID:floydhub,项目名称:floyd-cli,代码行数:10,代码来源:module.py

示例6: RequestQueueProgress

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def RequestQueueProgress(request_id):
	request_details = clc.Queue.GetStatus(request_id,silent=True)
	p = progress.Bar(label="%s  " % (request_details['RequestTitle']), expected_size=100)
	while True:
		p.show(request_details['PercentComplete'])
		if request_details['CurrentStatus'] in ('Succeeded','Failed'): break
		time.sleep(2)
		request_details = clc.v1.Queue.GetStatus(request_id,silent=True)
	p.done()
	if request_details['CurrentStatus'] == 'Succeeded':  Status('SUCCESS',1,"%s - %s" % (request_details['RequestTitle'],request_details['ProgressDesc']))
	elif request_details['CurrentStatus'] == 'Failed':  Status('ERROR',3,"%s - %s" % (request_details['RequestTitle'],request_details['ProgressDesc'])) 
开发者ID:CenturyLinkCloud,项目名称:clc-python-sdk,代码行数:13,代码来源:output.py

示例7: RequestBlueprintProgress

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def RequestBlueprintProgress(request_id,location,alias,quiet=False):
	time_start = time.time()
	time_task_start = time_start
	request_details = clc.v1.Blueprint.GetStatus(request_id,location,alias,silent=True)
	description = request_details['Description']
	Status('SUCCESS',1,request_details['Description'])
	if not quiet:  p = progress.Bar(expected_size=100)
	while True:
		if description != request_details['Description']:
			description = request_details['Description']
			if not quiet:  sys.stdout.write("\033[K")	# clear line
			Status('SUCCESS',1,"%s - %s" % (request_details['Description'],sec_to_time(int(time.time()-time_task_start))))
			time_task_start = time.time()
		if not quiet:  p.show(request_details['PercentComplete'])
		if request_details['CurrentStatus'] in ('Succeeded','Failed'): break
		time.sleep(2)
		request_details = clc.v1.Blueprint.GetStatus(request_id,location,alias,silent=True)
	#p.done()
	if not quiet:  sys.stdout.write("\033[K")	# clear line
	duration_secs = int(time.time()-time_start)
	if request_details['CurrentStatus'] == 'Succeeded':  Status('SUCCESS',1,"%s - %s" % (request_details['Description'],sec_to_time(duration_secs)))
	elif request_details['CurrentStatus'] == 'Failed':  Status('ERROR',3,"%s - %s" % (request_details['Description'],sec_to_time(duration_secs)))

	servers = []
	for server in request_details['Servers']:  servers.append({'Server': server})
	return(servers) 
开发者ID:CenturyLinkCloud,项目名称:clc-python-sdk,代码行数:28,代码来源:output.py

示例8: _upload

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def _upload(service, filename, file, password=None):
    filename = os.path.basename(filename)

    send = FFSend(service)

    mimetype = mimetypes.guess_type(filename, strict=False)[0] or 'application/octet-stream'
    print("Uploading as mimetype", mimetype)
    file.seek(0, 2)
    filesize = file.tell()
    file.seek(0)

    metadata = single_file_metadata(filename, filesize, mimetype=mimetype)

    bar = ProgressBar(expected_size=filesize or 1, filled_char='=')

    class FakeFile:
        def read(self, sz=None):
            res = file.read(sz)
            bar.show(file.tell())
            return res

    res, secret = send.upload(metadata, FakeFile())
    print()
    url = res['url'] + '#' + url_b64encode(secret)
    owner_token = res['owner']

    if password is not None:
        service, fid, secret = parse_url(url)
        send.owner_set_password(fid, owner_token, secret, password, url)

    print("Your download link is", url)
    print("Owner token is", owner_token)
    return url, owner_token 
开发者ID:nneonneo,项目名称:ffsend,代码行数:35,代码来源:ffsend.py

示例9: download

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def download(service, fid, secret, dest, password=None, url=None):
    send = FFSend(service)
    metadata = send.get_metadata(fid, secret, password, url)

    filename = metadata['metadata']['name']

    if os.path.isdir(dest):
        filename = os.path.join(dest, filename)
    else:
        filename = dest

    print("Downloading to %s..." % filename)

    try:
        with open(filename + '.tmp', 'wb') as outf:
            bar = ProgressBar(expected_size=metadata['metadata']['size'] or 1, filled_char='=')

            class FakeFile:
                def write(self, data):
                    res = outf.write(data)
                    bar.show(outf.tell())
                    return res

            send.download(fid, secret, FakeFile(), password, url)

    except Exception as e:
        print("File download failed:", e)
        os.unlink(filename + '.tmp')
    else:
        os.rename(filename + '.tmp', filename)
        print("Done, file verified!") 
开发者ID:nneonneo,项目名称:ffsend,代码行数:33,代码来源:ffsend.py

示例10: _writeSectors

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def _writeSectors(self, offset, data, tries=3):
        """Write one or more sectors with data

        This method clears the sectors before writing to them and checks
        for valid data via reading each page and comparing the checksum.
        """
        assert offset % self.sector_size == 0
        pages_offset = offset // self.page_size
        sectors_offset = offset // self.sector_size

        assert len(data) % self.sector_size == 0
        page_count = len(data) // self.page_size
        sector_count = len(data) // self.sector_size

        with progress.Bar(expected_size=page_count) as bar:
            sector_write_attempt = 0
            sector = 0
            while sector < sector_count:
                sector_index = sectors_offset + sector

                bar.show(sector * self.pages_per_sector)

                # Erase sector up to 'tries' times
                for _ in range(tries):
                    if self._eraseSector(sector_index):
                        break
                else:  # No erase was successful
                    logError('Could not erase sector 0x%08x' % sector_index)
                    return False

                for page in range(self.pages_per_sector):
                    page_data_index = sector * self.pages_per_sector + page
                    data_index = page_data_index * self.page_size
                    page_index = pages_offset + page_data_index

                    if self._writePage(page_index, data[data_index: data_index + self.page_size]):
                        bar.show(page_data_index + 1)
                        continue

                    sector_write_attempt += 1
                    if sector_write_attempt < tries:
                        break  # Retry sector

                    logError('Could not write page 0x%08x' % page_index)
                    return False

                else:  # All pages written normally -> next sector
                    sector += 1

        return True 
开发者ID:nfd,项目名称:spi-flash-programmer,代码行数:52,代码来源:spi_flash_programmer_client.py

示例11: verifyWithFile

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def verifyWithFile(self, filename, flash_offset=0, file_offset=0, length=DEFAULT_FLASH_SIZE):
        """Verify the flash content by checking against the file

        This method only uses checksums to verify the data integrity.
        """
        if length % self.page_size != 0:
            logError('length must be a multiple of the page size %d' % self.page_size)
            return False

        if flash_offset % self.page_size != 0:
            logError('flash_offset must be a multiple of the page size %d' % self.page_size)
            return False

        page_count = length // self.page_size
        pages_offset = flash_offset // self.page_size

        try:
            with open(filename, 'rb') as file:
                file.seek(file_offset)

                with progress.Bar(expected_size=page_count) as bar:
                    for page in range(page_count):
                        bar.show(page)

                        data = file.read(self.page_size)

                        page_index = pages_offset + page
                        crc = self._loadPageMultiple(page_index)
                        if crc is None:
                            logError('Could not read page 0x%08x' % page_index)
                            return True

                        if crc == binascii.crc32(data):
                            logOk('Page 0x%08x OK' % page_index)
                        else:
                            logError('Page 0x%08x invalid' % page_index)

                    bar.show(page_count)

            logOk('Done')
            return True
        except IOError:
            logError('Could not write to file \'%s\'' % filename)
            return True 
开发者ID:nfd,项目名称:spi-flash-programmer,代码行数:46,代码来源:spi_flash_programmer_client.py

示例12: create_tarfile

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def create_tarfile(self):
        """
        Create a tar file with the contents of the current directory
        """
        floyd_logger.info("Compressing data...")
        # Show progress bar (file_compressed/file_to_compress)
        self.__compression_bar = ProgressBar(expected_size=self.__files_to_compress, filled_char='=')

        # Auxiliary functions
        def dfilter_file_counter(tarinfo):
            """
            Dummy filter function used to track the progression at file levels.
            """
            self.__compression_bar.show(self.__files_compressed)
            self.__files_compressed += 1
            return tarinfo

        def warn_purge_exit(info_msg, filename, progress_bar, exit_msg):
            """
            Warn the user that's something went wrong,
            remove the tarball and provide an exit message.
            """
            progress_bar.done()
            floyd_logger.info(info_msg)
            rmtree(os.path.dirname(filename))
            sys.exit(exit_msg)

        try:
            # Define the default signal handler for catching: Ctrl-C
            signal.signal(signal.SIGINT, signal.default_int_handler)
            with tarfile.open(self.filename, "w:gz") as tar:
                tar.add(self.source_dir, arcname=os.path.basename(self.source_dir), filter=dfilter_file_counter)
            self.__compression_bar.done()
        except (OSError, IOError) as e:
            # OSError: [Errno 13] Permission denied
            if e.errno == errno.EACCES:
                self.source_dir = os.getcwd() if self.source_dir == '.' else self.source_dir  # Expand cwd
                warn_purge_exit(info_msg="Permission denied. Removing compressed data...",
                                filename=self.filename,
                                progress_bar=self.__compression_bar,
                                exit_msg=("Permission denied. Make sure to have read permission "
                                          "for all the files and directories in the path: %s")
                                % (self.source_dir))
            # OSError: [Errno 28] No Space Left on Device (IOError on python2.7)
            elif e.errno == errno.ENOSPC:
                dir_path = os.path.dirname(self.filename)
                warn_purge_exit(info_msg="No space left. Removing compressed data...",
                                filename=self.filename,
                                progress_bar=self.__compression_bar,
                                exit_msg=("No space left when compressing your data in: %s.\n"
                                          "Make sure to have enough space before uploading your data.")
                                % (os.path.abspath(dir_path)))

        except KeyboardInterrupt:  # Purge tarball on Ctrl-C
            warn_purge_exit(info_msg="Ctrl-C signal detected: Removing compressed data...",
                            filename=self.filename,
                            progress_bar=self.__compression_bar,
                            exit_msg="Stopped the data upload gracefully.") 
开发者ID:floydhub,项目名称:floyd-cli,代码行数:60,代码来源:files.py

示例13: resume_upload

# 需要导入模块: from clint.textui import progress [as 别名]
# 或者: from clint.textui.progress import Bar [as 别名]
def resume_upload(self,
                      file_path,
                      file_endpoint,
                      chunk_size=None,
                      headers=None,
                      auth=None,
                      offset=None):
        chunk_size = chunk_size or self.chunk_size

        try:
            offset = self._get_offset(file_endpoint, headers=headers, auth=auth)
        except LockedException:
            floyd_logger.error("Server busy handling last uploaded part, please wait and try again later.")
            return False
        except FloydException as e:
            floyd_logger.error(
                "Failed to fetch offset data from upload server! %s",
                e.message)
            return False
        except requests.exceptions.ConnectionError:
            floyd_logger.error(
                "Cannot connect to the Floyd data upload server for offset. "
                "Check your internet connection.")
            return False

        total_sent = 0
        file_size = os.path.getsize(file_path)

        with open(file_path, 'rb') as f:

            pb = ProgressBar(filled_char="=", expected_size=file_size)
            while offset < file_size:
                pb.show(offset)
                f.seek(offset)
                data = f.read(chunk_size)
                try:
                    offset = self._upload_chunk(data, offset, file_endpoint, headers=headers, auth=auth)
                    total_sent += len(data)
                    floyd_logger.debug("%s bytes sent", total_sent)
                except FloydException as e:
                    floyd_logger.error(
                        "Failed to fetch offset data from upload server! %s",
                        e.message)
                    return False
                except requests.exceptions.ConnectionError:
                    floyd_logger.error(
                        "Cannot connect to the Floyd data upload server. "
                        "Check your internet connection.")
                    return False

            # Complete the progress bar with one more call to show()
            pb.show(offset)
            pb.done()
        return True 
开发者ID:floydhub,项目名称:floyd-cli,代码行数:56,代码来源:tus_data.py


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