Python clint.textui.colored.yellow() Examples

The following are 29 code examples of clint.textui.colored.yellow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module clint.textui.colored , or try the search function .
Example #1
Source File: iptv.py    From IPTV with MIT License 6 votes vote down vote up
def menu():
    print ""
    print colored.yellow("################")
    print colored.yellow("##### IPTV #####")
    print colored.yellow("##### v" + cr.version + " ###")
    print colored.yellow("################")
    print ""
    print colored.blue("Menu")
    print "0 - Exit"
    print "1 - Search for some Servers"
    print "2 - Look at the servers list"
    print "3 - Select language, default is Italian"
    print "4 - Brute force all server from the list"
    print "5 - Brute force random server from the list"
    print "6 - Brute force specific server from the list"
    print "7 - Provide a random server to attack"
    print "" 
Example #2
Source File: i18ntool.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def usage(exit=True, code=1):
    print(u"i18n wrapper script for formhub.\n")
    with indent(4):
        puts(colored.yellow(u",/i18ntool.py add --lang <lang>"))
        puts(u"Create required files for enabling translation "
             u"of language with code <lang>\n")

        puts(colored.yellow(u"./i18ntool.py refresh [--lang <lang>]"))
        puts(u"Update the PO file for <lang> based on code.\n"
             u"<lang> is optionnal as we only use EN and do "
             u"all translations in Transifex.\n")

        puts(colored.yellow(u"./i18ntool.py update --user <tx_user> "
                            u"--password <tx_pass> [--lang <lang>]"))
        puts(u"Downloads new PO files for <lang> (or all) from Transifex "
             u"then compiles new MO files\n")

        puts(colored.yellow(u"./i18ntool.py compile [--lang <lang>]"))
        puts(u"Compiles all PO files for <lang> (or all) into MO files.\n"
             u"Not required unless you want to.\n")

    if exit:
        sys.exit(code) 
Example #3
Source File: __init__.py    From s3tk with MIT License 6 votes vote down vote up
def fix_check(klass, buckets, dry_run, fix_args={}):
    for bucket in fetch_buckets(buckets):
        check = klass(bucket)
        check.perform()

        if check.status == 'passed':
            message = colored.green('already ' + check.pass_message)
        elif check.status == 'denied':
            message = colored.red('access denied')
        else:
            if dry_run:
                message = colored.yellow('to be ' + check.pass_message)
            else:
                try:
                    check.fix(fix_args)
                    message = colored.blue('just ' + check.pass_message)
                except botocore.exceptions.ClientError as e:
                    message = colored.red(str(e))

        puts(bucket.name + ' ' + message) 
Example #4
Source File: __init__.py    From s3tk with MIT License 6 votes vote down vote up
def scan_object(bucket_name, key):
    obj = s3().Object(bucket_name, key)
    str_key = unicode_key(key)

    try:
        mode = determine_mode(obj.Acl())

        if mode == 'private':
            puts(str_key + ' ' + colored.green(mode))
        else:
            puts(str_key + ' ' + colored.yellow(mode))

        return mode
    except (botocore.exceptions.ClientError, botocore.exceptions.NoCredentialsError) as e:
        puts(str_key + ' ' + colored.red(str(e)))
        return 'error' 
Example #5
Source File: __init__.py    From s3tk with MIT License 6 votes vote down vote up
def reset_object(bucket_name, key, dry_run, acl):
    obj = s3().Object(bucket_name, key)
    str_key = unicode_key(key)

    try:
        obj_acl = obj.Acl()
        mode = determine_mode(obj_acl)

        if mode == acl:
            puts(str_key + ' ' + colored.green('ACL already ' + acl))
            return 'ACL already ' + acl
        elif dry_run:
            puts(str_key + ' ' + colored.yellow('ACL to be updated to ' + acl))
            return 'ACL to be updated to ' + acl
        else:
            obj_acl.put(ACL=acl)
            puts(str_key + ' ' + colored.blue('ACL updated to ' + acl))
            return 'ACL updated to ' + acl

    except (botocore.exceptions.ClientError, botocore.exceptions.NoCredentialsError) as e:
        puts(str_key + ' ' + colored.red(str(e)))
        return 'error' 
Example #6
Source File: actions.py    From stakkr with Apache License 2.0 6 votes vote down vote up
def get_services_urls(self):
        """Once started, displays a message with a list of running containers."""
        self.init_project()

        cts = docker.get_running_containers(self.project_name)[1]

        text = ''
        for _, ct_info in cts.items():
            service_config = self.config['services'][ct_info['compose_name']]
            if ({'service_name', 'service_url'} <= set(service_config)) is False:
                continue

            url = self.get_url(service_config['service_url'], ct_info['compose_name'])
            name = colored.yellow(service_config['service_name'])

            text += '  - For {}'.format(name).ljust(55, ' ') + ' : ' + url + '\n'

            if 'service_extra_ports' in service_config:
                ports = ', '.join(map(str, service_config['service_extra_ports']))
                text += ' '*4 + '(In your containers use the host '
                text += '"{}" and port(s) {})\n'.format(ct_info['compose_name'], ports)

        return text 
Example #7
Source File: mech.py    From mech with MIT License 6 votes vote down vote up
def pause(self, arguments):
        """
        Pauses the Mech machine.

        Usage: mech pause [options] [<instance>]

        Options:
            -h, --help                       Print this help
        """
        instance_name = arguments['<instance>']
        instance_name = self.activate(instance_name)

        vmrun = VMrun(self.vmx, user=self.user, password=self.password)
        if vmrun.pause() is None:
            puts_err(colored.red("Not paused", vmrun))
        else:
            puts_err(colored.yellow("Paused", vmrun)) 
Example #8
Source File: actions.py    From stakkr with Apache License 2.0 6 votes vote down vote up
def get_url(self, service_url: str, service: str):
        """Build URL to be displayed."""
        proxy_conf = self.config['proxy']
        # By default our URL is the IP
        url = docker.get_ct_item(service, 'ip')
        # If proxy enabled, display nice urls
        if bool(proxy_conf['enabled']):
            http_port = int(proxy_conf['http_port'])
            url = docker.get_ct_item(service, 'traefik_host').lower()
            url += '' if http_port == 80 else ':{}'.format(http_port)
        elif os_name() in ['Windows', 'Darwin']:
            puts(colored.yellow('[WARNING]') + ' Under Win and Mac, you need the proxy enabled')

        urls = [service_url.format(url) for url in url.split(',')]

        return ' / '.join(urls) 
Example #9
Source File: ui.py    From pgrepup with GNU General Public License v3.0 5 votes vote down vote up
def output_hint(hint):
    print("    " + colored.yellow("Hint: " + hint)) 
Example #10
Source File: runner.py    From polytester with MIT License 5 votes vote down vote up
def handle_keyboard_exception(self):
        puts()
        puts(colored.yellow("Keyboard interrupt. Stopping tests."))
        sys.exit(1) 
Example #11
Source File: text.py    From slack-machine with MIT License 5 votes vote down vote up
def warn(warn_string):
    puts(colored.yellow(f"Warning: {warn_string}")) 
Example #12
Source File: tag-bit9.py    From community with MIT License 5 votes vote down vote up
def tag_computer(self, computername, description, computertag):
    	print colored.yellow("[*] Finding "+computername)
        result = self.find_computer(computername)
        computerid = str(result[0]['id'])
        print colored.green("[+] "+computername+" ID="+computerid)
        data = {'description':description, 'computerTag': computertag}
        print colored.yellow("[*] Tagging "+computername)
        r = requests.put(self.computerurl+computerid, json.dumps(data), headers=self.authJson, verify=self.b9StrongCert)
        r.raise_for_status()
        result = r.json()
        print colored.green("[+] Tag Succeeded! ...waiting...\n")
        time.sleep(.07) 
Example #13
Source File: cl_utils.py    From bcwallet with Apache License 2.0 5 votes vote down vote up
def debug_print(to_print):
    if type(to_print) is dict:
        to_print = json.dumps(to_print, cls=DateTimeEncoder, indent=2)
    puts(colored.yellow(str(to_print))) 
Example #14
Source File: mech.py    From mech with MIT License 5 votes vote down vote up
def reload(self, arguments):
        """
        Restarts Mech machine, loads new Mechfile configuration.

        Usage: mech reload [options] [<instance>]

        Options:
                --provision                  Enable provisioning
            -h, --help                       Print this help
        """
        instance_name = arguments['<instance>']
        instance_name = self.activate(instance_name)

        vmrun = VMrun(self.vmx, user=self.user, password=self.password)

        puts_err(colored.blue("Reloading machine..."))
        started = vmrun.reset()
        if started is None:
            puts_err(colored.red("VM not restarted"))
        else:
            time.sleep(3)
            puts_err(colored.blue("Getting IP address..."))
            lookup = self.get("enable_ip_lookup", False)
            ip = vmrun.getGuestIPAddress(lookup=lookup)
            if ip:
                if started:
                    puts_err(colored.green("VM started on {}".format(ip)))
                else:
                    puts_err(colored.yellow("VM already was started on {}".format(ip)))
            else:
                if started:
                    puts_err(colored.green("VM started on an unknown IP address"))
                else:
                    puts_err(colored.yellow("VM already was started on an unknown IP address")) 
Example #15
Source File: error.py    From datacats with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, message, parent_exception=None):
        self.message = message
        if parent_exception and hasattr(parent_exception, 'user_description'):
            vals = {
                "original": self.message,
                "type_description": parent_exception.user_description,
                "message": str(parent_exception),
            }
            self.message = "".join([str(colored.blue("{original}\n\n")),
                                    "-" * 30,
                                    "\n{type_description}:\n",
                                    str(colored.yellow("{message}\n"))]
                                    ).format(**vals)

        super(DatacatsError, self).__init__(message) 
Example #16
Source File: version.py    From orbital with MIT License 5 votes vote down vote up
def release():
    """Bump version, tag, build, gen docs."""
    if check_staged():
        raise EnvironmentError('There are staged changes, abort.')
    if check_unstaged():
        raise EnvironmentError('There are unstaged changes, abort.')
    bump()
    tag()
    build()
    doc_gen()
    puts(colored.yellow("Remember to upload documentation and package:"))
    with indent(2):
        puts(colored.cyan("shovel doc.upload"))
        puts(colored.cyan("shovel version.upload")) 
Example #17
Source File: actions.py    From stakkr with Apache License 2.0 5 votes vote down vote up
def _is_up(self, container: str):
        try:
            docker.check_cts_are_running(self.project_name)
        except SystemError:
            return

        if container is None:
            puts(colored.yellow('[INFO]') + ' stakkr is already started ...')
            sys.exit(0)

        # If single container : check if that specific one is running
        ct_name = docker.get_ct_item(container, 'name')
        if docker.container_running(ct_name):
            puts(colored.yellow('[INFO]') + ' service {} is already started ...'.format(container))
            sys.exit(0) 
Example #18
Source File: actions.py    From stakkr with Apache License 2.0 5 votes vote down vote up
def status(self):
        """Return a nice table with the list of started containers."""
        self.init_project()

        try:
            docker.check_cts_are_running(self.project_name)
        except SystemError:
            puts(colored.yellow('[INFO]') + ' stakkr is currently stopped')
            sys.exit(0)

        _, cts = docker.get_running_containers(self.project_name)

        _print_status_headers()
        _print_status_body(cts) 
Example #19
Source File: __init__.py    From s3tk with MIT License 5 votes vote down vote up
def update_policy(bucket, encryption=None, dry_run=False):
    bucket = s3().Bucket(bucket)

    policy = fetch_policy(bucket)
    if not policy:
        policy = OrderedDict([
            ('Version', '2012-10-17'),
            ('Statement', [])
        ])

    es = encryption_statement(bucket)
    es_index = next((i for i, s in enumerate(policy['Statement']) if statement_matches(s, es)), -1)

    if es_index != -1:
        if encryption:
            puts("No encryption change")
            print_policy(policy)
        elif encryption is False:
            puts("Removing encryption")
            policy['Statement'].pop(es_index)
            print_policy(policy)

            if not dry_run:
                if any(policy['Statement']):
                    bucket.Policy().put(Policy=json.dumps(policy))
                else:
                    bucket.Policy().delete()
    else:
        if encryption:
            puts("Adding encryption")
            policy['Statement'].append(es)
            print_policy(policy)

            if not dry_run:
                bucket.Policy().put(Policy=json.dumps(policy))
        elif encryption is False:
            puts(colored.yellow("No encryption change"))
            print_policy(policy) 
Example #20
Source File: __init__.py    From s3tk with MIT License 5 votes vote down vote up
def list_policy(buckets, named=False):
    for bucket in fetch_buckets(buckets):
        puts(bucket.name)

        policy = fetch_policy(bucket)

        with indent(2):
            if policy is None:
                puts(colored.yellow('None'))
            else:
                if named:
                    public = public_statement(bucket)
                    no_object_acl = no_object_acl_statement(bucket)
                    public_uploads = public_uploads_statement(bucket)
                    no_uploads = no_uploads_statement(bucket)
                    encryption = encryption_statement(bucket)

                    for statement in policy['Statement']:
                        if statement_matches(statement, public):
                            named_statement = 'Public'
                        elif statement_matches(statement, no_object_acl):
                            named_statement = 'No object ACL'
                        elif statement_matches(statement, public_uploads):
                            named_statement = 'Public uploads'
                        elif statement_matches(statement, no_uploads):
                            named_statement = 'No uploads'
                        elif statement_matches(statement, encryption):
                            named_statement = 'Encryption'
                        else:
                            named_statement = 'Custom'

                        puts(colored.yellow(named_statement))

                else:
                    puts(colored.yellow(json.dumps(policy, indent=4)))

        puts() 
Example #21
Source File: __init__.py    From s3tk with MIT License 5 votes vote down vote up
def notice(message):
    puts(colored.yellow(message)) 
Example #22
Source File: ui.py    From pgrepup with GNU General Public License v3.0 5 votes vote down vote up
def output_cli_result(result, compensation=0):
    if isinstance(result, bool):
        text = colored.green('OK') if result else colored.red('KO')
    else:
        text = colored.yellow(result)

    return '.' * (80 - this.current_position - len(text) - compensation) + text 
Example #23
Source File: install.py    From datacats with GNU Affero General Public License v3.0 4 votes vote down vote up
def install_all(environment, clean, verbose=False, quiet=False, packages=None):
    logs = check_connectivity()
    if logs.strip():
        raise DatacatsError(logs)

    if clean:
        clean_pyc(environment, quiet)

    srcdirs = set()
    reqdirs = set()
    for d in listdir(environment.target):
        fulld = environment.target + '/' + d
        if not isdir(fulld):
            continue
        if not exists(fulld + '/setup.py'):
            continue
        if packages and d not in packages:
            continue
        srcdirs.add(d)
        if (exists(fulld + '/requirements.txt') or
                exists(fulld + '/pip-requirements.txt')):
            reqdirs.add(d)

    try:
        if not packages or 'ckan' in packages:
            srcdirs.remove('ckan')
            reqdirs.remove('ckan')
            srcdirs = ['ckan'] + sorted(srcdirs)
            reqdirs = ['ckan'] + sorted(reqdirs)
    except KeyError:
        raise DatacatsError('ckan not found in environment directory')

    if clean:
        environment.clean_virtualenv()
        environment.install_extra()

    for s in srcdirs:
        if verbose:
            print colored.yellow('Installing ' + s + '\n')
        elif not quiet:
            print 'Installing ' + s
        environment.install_package_develop(s, sys.stdout if verbose and not quiet else None)
        if verbose and not quiet:
            print
    for s in reqdirs:
        if verbose:
            print colored.yellow('Installing ' + s + ' requirements' + '\n')
        elif not quiet:
            print 'Installing ' + s + ' requirements'
        environment.install_package_requirements(s, sys.stdout if verbose and not quiet else None)
        if verbose:
            print 
Example #24
Source File: mech.py    From mech with MIT License 4 votes vote down vote up
def up(self, arguments):
        """
        Starts and provisions the mech environment.

        Usage: mech up [options] [<instance>]

        Options:
                --gui                        Start GUI
                --provision                  Enable provisioning
                --insecure                   Do not validate SSL certificates
                --cacert FILE                CA certificate for SSL download
                --capath DIR                 CA certificate directory for SSL download
                --cert FILE                  A client SSL cert, if needed
                --checksum CHECKSUM          Checksum for the box
                --checksum-type TYPE         Checksum type (md5, sha1, sha256)
                --no-cache                   Do not save the downloaded box
            -h, --help                       Print this help
        """
        gui = arguments['--gui']
        save = not arguments['--no-cache']
        requests_kwargs = utils.get_requests_kwargs(arguments)

        instance_name = arguments['<instance>']
        instance_name = self.activate(instance_name)

        utils.index_active_instance(instance_name)

        vmx = utils.init_box(self.box_name, self.box_version, requests_kwargs=requests_kwargs, save=save)
        vmrun = VMrun(vmx, user=self.user, password=self.password)
        puts_err(colored.blue("Bringing machine up..."))
        started = vmrun.start(gui=gui)
        if started is None:
            puts_err(colored.red("VM not started"))
        else:
            time.sleep(3)
            puts_err(colored.blue("Getting IP address..."))
            lookup = self.get("enable_ip_lookup", False)
            ip = vmrun.getGuestIPAddress(lookup=lookup)
            puts_err(colored.blue("Sharing current folder..."))
            vmrun.enableSharedFolders()
            vmrun.addSharedFolder('mech', os.getcwd(), quiet=True)
            if ip:
                if started:
                    puts_err(colored.green("VM started on {}".format(ip)))
                else:
                    puts_err(colored.yellow("VM was already started on {}".format(ip)))
            else:
                if started:
                    puts_err(colored.green("VM started on an unknown IP address"))
                else:
                    puts_err(colored.yellow("VM was already started on an unknown IP address")) 
Example #25
Source File: mech.py    From mech with MIT License 4 votes vote down vote up
def resume(self, arguments):
        """
        Resume a paused/suspended Mech machine.

        Usage: mech resume [options] [<instance>]

        Options:
                --provision                  Enable provisioning
            -h, --help                       Print this help
        """
        instance_name = arguments['<instance>']
        instance_name = self.activate(instance_name)

        utils.index_active_instance(instance_name)

        vmrun = VMrun(self.vmx, user=self.user, password=self.password)

        # Try to unpause
        if vmrun.unpause(quiet=True) is not None:
            time.sleep(1)
            puts_err(colored.blue("Getting IP address..."))
            lookup = self.get("enable_ip_lookup", False)
            ip = vmrun.getGuestIPAddress(lookup=lookup)
            if ip:
                puts_err(colored.green("VM resumed on {}".format(ip)))
            else:
                puts_err(colored.green("VM resumed on an unknown IP address"))

        # Otherwise try starting
        else:
            started = vmrun.start()
            if started is None:
                puts_err(colored.red("VM not started"))
            else:
                time.sleep(3)
                puts_err(colored.blue("Getting IP address..."))
                lookup = self.get("enable_ip_lookup", False)
                ip = vmrun.getGuestIPAddress(lookup=lookup)
                puts_err(colored.blue("Sharing current folder..."))
                vmrun.enableSharedFolders()
                vmrun.addSharedFolder('mech', os.getcwd(), quiet=True)
                if ip:
                    if started:
                        puts_err(colored.green("VM started on {}".format(ip)))
                    else:
                        puts_err(colored.yellow("VM already was started on {}".format(ip)))
                else:
                    if started:
                        puts_err(colored.green("VM started on an unknown IP address"))
                    else:
                        puts_err(colored.yellow("VM already was started on an unknown IP address")) 
Example #26
Source File: mech.py    From mech with MIT License 4 votes vote down vote up
def list(self, arguments):
        """
        Lists all available boxes.

        Usage: mech list [options]

        Options:
            -h, --help                       Print this help
        """
        print("{}\t{}\t{}\t{}\t{}".format(
            'NAME'.rjust(20),
            'ADDRESS'.rjust(15),
            'BOX'.rjust(35),
            'VERSION'.rjust(12),
            'PATH',
        ))
        for instance_name, instance in utils.instances().items():
            path = instance.get('path')
            if path and os.path.exists(path):
                self.activate(instance_name)
                mech_path = os.path.join(path, '.mech')
                if os.path.exists(mech_path):
                    vmx = self.get_vmx(silent=True)
                    if vmx:
                        vmrun = VMrun(vmx, user=self.user, password=self.password)
                        lookup = self.get("enable_ip_lookup", False)
                        ip = vmrun.getGuestIPAddress(wait=False, quiet=True, lookup=lookup)
                    else:
                        ip = colored.red("invalid")
                    if ip is None:
                        ip = colored.yellow("poweroff")
                    elif not ip:
                        ip = colored.green("running")
                    else:
                        ip = colored.green(ip)
                else:
                    ip = ""
                box_name = self.box_name or ""
                box_version = self.box_version or ""
                print("{}\t{}\t{}\t{}\t{}".format(
                    colored.green(instance_name.rjust(20)),
                    ip.rjust(15),
                    box_name.rjust(35),
                    box_version.rjust(12),
                    path,
                )) 
Example #27
Source File: eDNsaliency_batch.py    From flickr-cropping-dataset with MIT License 4 votes vote down vote up
def batchProcess(imgPath, outPath, opts):
    # read eDN model(s)
    descFile = open(opts.descPath, 'r')
    desc = pickle.load(descFile)
    descFile.close()

    nFeatures = np.sum([d['desc'][-1][0][1]['initialize']['n_filters']
                    for d in desc if d != None])

    # load SVM model and whitening parameters
    svm = load_model(opts.svmPath)
    f = open(opts.whitePath, 'r')
    whiteParams = np.asarray([map(float, line.split(' ')) for line in f]).T
    f.close()

    # assemble svm model
    svmModel = {}
    svmModel['svm'] = svm
    svmModel['whitenParams'] = whiteParams

    biasToCntr = (svm.get_nr_feature()-nFeatures) == 1

    model = EDNSaliencyModel(desc, svmModel, biasToCntr)

    puts(colored.yellow("Collecting image filenames..."))
    todo_list = [ f for f in listdir(imgPath) if isfile(join(imgPath,f)) ]
    existing_list = [ f for f in listdir(outPath) if isfile(join(outPath,f)) ]
    #image_list.sort()
    puts("Done")

    for f in todo_list:
        if f not in existing_list:
            print '-------------------------------------------------------------'
            print 'processing', f
            print

            try:
                # read image
                img = misc.imread(join(imgPath,f))
                # compute saliency map
                salMap = model.saliency(img, normalize=False)
                # normalize and save the saliency map to disk
                normSalMap = (255.0 / (salMap.max()-salMap.min()) *
                         (salMap-salMap.min())).astype(np.uint8)
                misc.imsave(join(outPath,f), normSalMap)

            except Exception as e:
                puts(colored.red('ERROR: {}'.format(e)))
                puts(colored.yellow('filename: {}'.format(f)))
        else:
            print '-------------------------------------------------------------'
            puts(colored.yellow('Saliency map already exists! ({})'.format(f)))
            print 
Example #28
Source File: __init__.py    From s3tk with MIT License 4 votes vote down vote up
def encrypt_object(bucket_name, key, dry_run, kms_key_id, customer_key):
    obj = s3().Object(bucket_name, key)
    str_key = unicode_key(key)

    try:
        if customer_key:
            obj.load(SSECustomerAlgorithm='AES256', SSECustomerKey=customer_key)

        encrypted = None
        if customer_key:
            encrypted = obj.sse_customer_algorithm is not None
        elif kms_key_id:
            encrypted = obj.server_side_encryption == 'aws:kms'
        else:
            encrypted = obj.server_side_encryption == 'AES256'

        if encrypted:
            puts(str_key + ' ' + colored.green('already encrypted'))
            return 'already encrypted'
        else:
            if dry_run:
                puts(str_key + ' ' + colored.yellow('to be encrypted'))
                return 'to be encrypted'
            else:
                copy_source = {'Bucket': bucket_name, 'Key': obj.key}

                # TODO support going from customer encryption to other forms
                if kms_key_id:
                    obj.copy_from(
                        CopySource=copy_source,
                        ServerSideEncryption='aws:kms',
                        SSEKMSKeyId=kms_key_id
                    )
                elif customer_key:
                    obj.copy_from(
                        CopySource=copy_source,
                        SSECustomerAlgorithm='AES256',
                        SSECustomerKey=customer_key
                    )
                else:
                    obj.copy_from(
                        CopySource=copy_source,
                        ServerSideEncryption='AES256'
                    )

                puts(str_key + ' ' + colored.blue('just encrypted'))
                return 'just encrypted'

    except (botocore.exceptions.ClientError, botocore.exceptions.NoCredentialsError) as e:
        puts(str_key + ' ' + colored.red(str(e)))
        return 'error' 
Example #29
Source File: chrome_driver.py    From DeleteFB with MIT License 4 votes vote down vote up
def get_webdriver(chrome_binary_path):
    """
     Ensure a webdriver is available
     If Not, Download it.
    """

    # Download it according to the current machine
    chrome_maj_version, chrome_webdriver = construct_driver_url(chrome_binary_path)

    driver_path = f"{cache_dir}/chromedriver{chrome_maj_version}"

    if exists(driver_path):
        return driver_path

    if not chrome_webdriver:
        raise UnknownOSException("Unknown Operating system platform")

    global total_size

    def show_progress(*res):
        global total_size
        pbar = None
        downloaded = 0
        block_num, block_size, total_size = res

        if not pbar:
            pbar = progressbar.ProgressBar(maxval=total_size)
            pbar.start()
        downloaded += block_num * block_size

        if downloaded < total_size:
            pbar.update(downloaded)
        else:
            pbar.finish()

    puts(colored.yellow("Downloading Chrome Webdriver"))
    file_name = f"{cache_dir}/{chrome_webdriver.split('/')[-1]}"
    response = urlretrieve(chrome_webdriver, file_name, show_progress)

    if int(response[1].get("Content-Length")) == total_size:
        puts(colored.green("Completed downloading the Chrome Driver."))

        return extract_zip(file_name, chrome_maj_version)

    else:
        puts(colored.red("An error Occurred While trying to download the driver."))
        # remove the downloaded file and exit
        os.remove(file_name)
        sys.stderr.write(NO_CHROME_DRIVER)
        sys.exit(1)