Python click.launch() Examples

The following are 23 code examples of click.launch(). 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 click , or try the search function .
Example #1
Source File: stackit_core.py    From stackit with MIT License 6 votes vote down vote up
def select(questions, num):
    print_full_question(questions[num - 1])
    working = True
    while working:
        user_input = click.prompt("Enter b to launch browser, x to return to search, or q to quit")
        if user_input == 'b':
            click.launch(questions[num - 1].json['link'])
        elif user_input == 'q':
            sys.exit()
        elif user_input == 'x':
            click.echo("\n" * 12)
            # Ranging over the 5 questions including the user's choice
            origin = 0
            if not num % NUM_RESULTS:
                origin = num - NUM_RESULTS
            else:
                origin = num - num % NUM_RESULTS
            for j in range(origin, origin + NUM_RESULTS):
                print_question(questions[j], j + 1)
            working = False
        else:
            click.echo(click.style(
                "The input entered was not recognized as a valid choice.",
                fg="red",
                err=True)) 
Example #2
Source File: common.py    From releasetool with Apache License 2.0 6 votes vote down vote up
def publish_via_kokoro(ctx: TagContext) -> None:
    kokoro_url = "https://fusion.corp.google.com/projectanalysis/current/KOKORO/"

    ctx.fusion_url = parse.urljoin(
        kokoro_url, parse.quote_plus(f"prod:{ctx.kokoro_job_name}")
    )

    if ctx.interactive:
        pyperclip.copy(ctx.release_tag)

        click.secho(
            "> Trigger the Kokoro build with the commitish below to publish to PyPI. The commitish has been copied to the clipboard.",
            fg="cyan",
        )

    click.secho(f"Kokoro build URL:\t\t{click.style(ctx.fusion_url, underline=True)}")
    click.secho(f"Commitish:\t{click.style(ctx.release_tag, bold=True)}")

    if ctx.interactive:
        if click.confirm("Would you like to go the Kokoro build page?", default=True):
            click.launch(ctx.fusion_url) 
Example #3
Source File: operations.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def dashboard(ctx, yes, url):
    """Open this operation's dashboard details in browser."""
    owner, project_name, run_uuid = get_project_run_or_local(
        ctx.obj.get("project"), ctx.obj.get("run_uuid"), is_cli=True,
    )
    dashboard_url = clean_host(settings.CLIENT_CONFIG.host)
    run_url = "{}/{}/{}/runs/{}/".format(dashboard_url, owner, project_name, run_uuid)
    if url:
        Printer.print_header("The dashboard is available at: {}".format(run_url))
        sys.exit(0)
    if not yes:
        click.confirm(
            "Dashboard page will now open in your browser. Continue?",
            abort=True,
            default=True,
        )
    click.launch(run_url) 
Example #4
Source File: cum.py    From cum with Apache License 2.0 5 votes vote down vote up
def open(alias):
    """Open the series URL in a browser."""
    s = db.Series.alias_lookup(alias)
    click.launch(s.url) 
Example #5
Source File: config.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def explore():
    """Open the config location in your file manager."""
    click.launch(CONFIG_FILE, locate=True) 
Example #6
Source File: main.py    From huobi with MIT License 5 votes vote down vote up
def document():
    """打开huobitrade文档"""
    click.launch('https://hadrianl.github.io/huobi/') 
Example #7
Source File: cli.py    From rio-glui with MIT License 5 votes vote down vote up
def glui(
    path,
    bidx,
    scale,
    colormap,
    tiles_format,
    tiles_dimensions,
    nodata,
    gl_tile_size,
    port,
    playground,
    mapbox_token,
):
    """Rasterio glui cli."""
    if scale and len(scale) not in [1, 3]:
        raise click.ClickException("Invalid number of scale values")

    raster = RasterTiles(path, indexes=bidx, tiles_size=tiles_dimensions, nodata=nodata)

    app = server.TileServer(
        raster,
        scale=scale,
        colormap=colormap,
        tiles_format=tiles_format,
        gl_tiles_size=gl_tile_size,
        gl_tiles_minzoom=raster.get_min_zoom(),
        gl_tiles_maxzoom=raster.get_max_zoom(),
        port=port,
    )

    if playground:
        url = app.get_playground_url()
    else:
        url = app.get_template_url()

    if mapbox_token:
        url = "{}?access_token={}".format(url, mapbox_token)

    click.launch(url)
    click.echo("Inspecting {} at {}".format(path, url), err=True)
    app.start() 
Example #8
Source File: web.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def launch_web_ui(cluster: Cluster) -> None:
    """
    Launch the web UI for a cluster.

    Args:
        cluster: The cluster to launch a web UI for.
    """
    master = next(iter(cluster.masters))
    web_ui = 'http://' + str(master.public_ip_address)
    click.launch(web_ui) 
Example #9
Source File: shell.py    From eavatar-me with Apache License 2.0 5 votes vote down vote up
def run(self):

        t = Thread(target=wrapper.launch, args=(self.inbox, self.outbox))
        t.setDaemon(True)
        t.start()

        self._run() 
Example #10
Source File: shell.py    From eavatar-me with Apache License 2.0 5 votes vote down vote up
def open_folder(self):
        click.launch(environ.get_app_dir()) 
Example #11
Source File: projects.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def dashboard(ctx, yes, url):
    """Open this operation's dashboard details in browser."""
    owner, project_name = get_project_or_local(ctx.obj.get("project"), is_cli=True)
    dashboard_url = clean_host(settings.CLIENT_CONFIG.host)
    project_url = "{}/{}/{}/".format(dashboard_url, owner, project_name)
    if url:
        Printer.print_header("The dashboard is available at: {}".format(project_url))
        sys.exit(0)
    if not yes:
        click.confirm(
            "Dashboard page will now open in your browser. Continue?",
            abort=True,
            default=True,
        )
    click.launch(project_url) 
Example #12
Source File: dashboard.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def dashboard(yes, url):
    """Open dashboard in browser."""
    dashboard_url = settings.CLIENT_CONFIG.host
    if url:
        click.echo(dashboard_url)
        sys.exit(0)
    if not yes:
        click.confirm(
            "Dashboard page will now open in your browser. Continue?",
            abort=True,
            default=True,
        )

    click.launch(dashboard_url) 
Example #13
Source File: cli.py    From stmocli with Mozilla Public License 2.0 5 votes vote down vote up
def view(stmo, file_name):
    """Opens a query in a browser.

    FILE_NAME: The filename of the tracked query SQL.

    Opens a browser window to the redash query.
    """
    try:
        url = stmo.url_for_query(file_name)
    except KeyError:
        click.echo("Couldn't find a query ID for {}: No such query, "
                   "maybe you need to 'track' first".format(file_name),
                   err=True)
        sys.exit(1)
    click.launch(url) 
Example #14
Source File: dashboard.py    From polyaxon-cli with MIT License 5 votes vote down vote up
def dashboard(yes, url):
    """Open dashboard in browser."""
    dashboard_url = "{}/app".format(PolyaxonClient().api_config.http_host)
    if url:
        click.echo(dashboard_url)
        sys.exit(0)
    if not yes:
        click.confirm('Dashboard page will now open in your browser. Continue?',
                      abort=True, default=True)

    click.launch(dashboard_url) 
Example #15
Source File: bottle_boilerplate.py    From bottle-boilerplate with MIT License 5 votes vote down vote up
def doc(version):
    if version not in ["dev", "0.12", "0.11", "0.10", "0.9"]:
        version = "dev"
    url = 'http://bottlepy.org/docs/{}/'.format(version)
    click.launch(url)
    click.echo(u'Bottle Boilerplate start browser!') 
Example #16
Source File: backend.py    From zotero-cli with MIT License 5 votes vote down vote up
def create_api_key():
        """ Interactively create a new API key via Zotero's OAuth API.

        Requires the user to enter a verification key displayed in the browser.

        :returns:   API key and the user's library ID
        """
        auth = OAuth1Service(
            name='zotero',
            consumer_key=CLIENT_KEY,
            consumer_secret=CLIENT_SECRET,
            request_token_url=REQUEST_TOKEN_URL,
            access_token_url=ACCESS_TOKEN_URL,
            authorize_url=AUTH_URL,
            base_url=BASE_URL)
        token, secret = auth.get_request_token(
            params={'oauth_callback': 'oob'})
        auth_url = auth.get_authorize_url(token)
        auth_url += '&' + urlencode({
            'name': 'zotero-cli',
            'library_access': 1,
            'notes_access': 1,
            'write_access': 1,
            'all_groups': 'read'})
        click.echo("Opening {} in browser, please confirm.".format(auth_url))
        click.launch(auth_url)
        verification = click.prompt("Enter verification code")
        token_resp = auth.get_raw_access_token(
            token, secret, method='POST',
            data={'oauth_verifier': verification})
        if not token_resp:
            logging.debug(token_resp.content)
            click.fail("Error during API key generation.")
        access = urlparse.parse_qs(token_resp.text)
        return access['oauth_token'][0], access['userID'][0] 
Example #17
Source File: cli.py    From zotero-cli with MIT License 5 votes vote down vote up
def read(ctx, item_id, with_note):
    """ Read an item attachment. """
    try:
        item_id = pick_item(ctx.obj, item_id)
    except ValueError as e:
        ctx.fail(e.args[0])
    read_att = None
    attachments = ctx.obj.attachments(item_id)
    if not attachments:
        ctx.fail("Could not find an attachment for reading.")
    elif len(attachments) > 1:
        click.echo("Multiple attachments available.")
        read_att = select([(att, att['data']['title'])
                           for att in attachments])
    else:
        read_att = attachments[0]

    att_path = ctx.obj.get_attachment_path(read_att)
    click.echo("Opening '{}'.".format(att_path))
    click.launch(str(att_path), wait=False)
    if with_note:
        existing_notes = list(ctx.obj.notes(item_id))
        if existing_notes:
            edit_existing = click.confirm("Edit existing note?")
            if edit_existing:
                note = pick_note(ctx, ctx.obj, item_id)
            else:
                note = None
        else:
            note = None
        note_body = click.edit(
            text=note['data']['note']['text'] if note else None,
            extension=get_extension(ctx.obj.note_format))
        if note_body and note is None:
            ctx.obj.create_note(item_id, note_body)
        elif note_body:
            note['data']['note']['text'] = note_body
            ctx.obj.save_note(note) 
Example #18
Source File: cli.py    From gimel with MIT License 5 votes vote down vote up
def dashboard(namespace):
    click.launch(dashboard_url(namespace)) 
Example #19
Source File: exception_handler.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def _process_open(self):
        """Open link in a browser."""
        click.launch(self._format_issue_url())
        if not click.confirm('Did it work?', default=True):
            click.echo()
            self._process_print()
            click.secho(
                '\nOpen the line manually and copy the text above\n',
                fg='yellow'
            )
            click.secho(
                '  ' + self.REPO_URL + self.ISSUE_SUFFIX + '\n', bold=True
            ) 
Example #20
Source File: cli.py    From PyCon2019-Click-Tutorial with Mozilla Public License 2.0 5 votes vote down vote up
def launch():
    """Launch applicaiton."""
    click.launch("https://click.palletsprojects.com/") 
Example #21
Source File: tools.py    From q2cli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def view(visualization_path, index_extension):
    # Guard headless envs from having to import anything large
    import sys
    from q2cli.core.config import CONFIG
    if not os.getenv("DISPLAY") and sys.platform != "darwin":
        raise click.UsageError(
            'Visualization viewing is currently not supported in headless '
            'environments. You can view Visualizations (and Artifacts) at '
            'https://view.qiime2.org, or move the Visualization to an '
            'environment with a display and view it with `qiime tools view`.')

    import zipfile
    import qiime2.sdk

    if index_extension.startswith('.'):
        index_extension = index_extension[1:]
    try:
        visualization = qiime2.sdk.Visualization.load(visualization_path)
    # TODO: currently a KeyError is raised if a zipped file that is not a
    # QIIME 2 result is passed. This should be handled better by the framework.
    except (zipfile.BadZipFile, KeyError, TypeError):
        raise click.BadParameter(
            '%s is not a QIIME 2 Visualization. Only QIIME 2 Visualizations '
            'can be viewed.' % visualization_path)

    index_paths = visualization.get_index_paths(relative=False)

    if index_extension not in index_paths:
        raise click.BadParameter(
            'No index %s file is present in the archive. Available index '
            'extensions are: %s' % (index_extension,
                                    ', '.join(index_paths.keys())))
    else:
        index_path = index_paths[index_extension]
        launch_status = click.launch(index_path)
        if launch_status != 0:
            click.echo(CONFIG.cfg_style('error', 'Viewing visualization '
                                        'failed while attempting to open '
                                        f'{index_path}'), err=True)
        else:
            while True:
                click.echo(
                    "Press the 'q' key, Control-C, or Control-D to quit. This "
                    "view may no longer be accessible or work correctly after "
                    "quitting.", nl=False)
                # There is currently a bug in click.getchar where translation
                # of Control-C and Control-D into KeyboardInterrupt and
                # EOFError (respectively) does not work on Python 3. The code
                # here should continue to work as expected when the bug is
                # fixed in Click.
                #
                # https://github.com/pallets/click/issues/583
                try:
                    char = click.getchar()
                    click.echo()
                    if char in {'q', '\x03', '\x04'}:
                        break
                except (KeyboardInterrupt, EOFError):
                    break 
Example #22
Source File: starred.py    From starred with MIT License 4 votes vote down vote up
def starred(username, token, sort, repository, message):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username maguowei --sort > README.md
    """
    if repository:
        if not token:
            click.secho('Error: create repository need set --token', fg='red')
            return
        file = BytesIO()
        sys.stdout = file
    else:
        file = None

    gh = GitHub(token=token)
    stars = gh.starred_by(username)
    click.echo(desc)
    repo_dict = {}

    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace('\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
        repo_dict[language].append([s.name, s.html_url, description.strip()])

    if sort:
        repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))

    for language in repo_dict.keys():
        data = u'  - [{}](#{})'.format(language, '-'.join(language.lower().split()))
        click.echo(data)
    click.echo('')

    for language in repo_dict:
        click.echo('## {} \n'.format(language.replace('#', '# #')))
        for repo in repo_dict[language]:
            data = u'- [{}]({}) - {}'.format(*repo)
            click.echo(data)
        click.echo('')

    click.echo(license_.format(username=username))

    if file:
        try:
            rep = gh.repository(username, repository)
            readme = rep.readme()
            readme.update(message, file.getvalue())
        except NotFoundError:
            rep = gh.create_repository(repository, 'A curated list of my GitHub stars!')
            rep.create_file('README.md', 'starred initial commit', file.getvalue())
        click.launch(rep.html_url) 
Example #23
Source File: operations.py    From polyaxon with Apache License 2.0 4 votes vote down vote up
def service(ctx, yes, external, url):
    """Open the operation service in browser.

    N.B. The operation must have a run kind service, otherwise it will raise an error.

    You can open the service embedded in Polyaxon UI or using the real service URL,
    please use the `--external` flag.
    """
    owner, project_name, run_uuid = get_project_run_or_local(
        ctx.obj.get("project"), ctx.obj.get("run_uuid"), is_cli=True,
    )
    client = RunClient(owner=owner, project=project_name, run_uuid=run_uuid)
    client.refresh_data()
    if client.run_data.kind != V1RunKind.SERVICE:
        Printer.print_warning(
            "Command expected a operations of "
            "kind `service` received kind: {}!".format(client.run_data.kind)
        )
        sys.exit(1)
    dashboard_url = clean_host(settings.CLIENT_CONFIG.host)

    Printer.print_header("Waiting for running condition ...")
    client.wait_for_condition(
        statuses={V1Statuses.RUNNING} | LifeCycle.DONE_VALUES, print_status=True
    )

    client.refresh_data()
    if LifeCycle.is_done(client.run_data.status):
        Printer.print_header("The operations reached a done statuses.")
        latest_status = Printer.add_status_color(
            {"status": client.run_data.status}, status_key="status"
        )
        click.echo("{}\n".format(latest_status["status"]))

    namespace = client.run_data.settings.namespace

    run_url = "{}/{}/{}/runs/{}/service".format(
        dashboard_url, owner, project_name, run_uuid
    )
    service_endpoint = SERVICES_V1
    if client.run_data.meta_info.get("rewrite_path", False):
        service_endpoint = REWRITE_SERVICES_V1
    external_run_url = "{}/{}/{}/{}/{}/runs/{}/".format(
        dashboard_url, service_endpoint, namespace, owner, project_name, run_uuid
    )
    if url:
        Printer.print_header("The service will be available at: {}".format(run_url))
        Printer.print_header(
            "You can also view it in an external link at: {}".format(external_run_url)
        )
        sys.exit(0)
    if not yes:
        click.confirm(
            "Dashboard page will now open in your browser. Continue?",
            abort=True,
            default=True,
        )
    if external:
        click.launch(external_run_url)
        sys.exit(0)
    click.launch(run_url)