python类prompt()的实例源码

decorators.py 文件源码 项目:uptick 作者: xeroc 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def unlock(f):
    """ This decorator will unlock the wallet by either asking for a
        passphrase or taking the environmental variable ``UNLOCK``
    """
    @click.pass_context
    def new_func(ctx, *args, **kwargs):
        if not ctx.obj.get("unsigned", False):
            if ctx.bitshares.wallet.created():
                if "UNLOCK" in os.environ:
                    pwd = os.environ["UNLOCK"]
                else:
                    pwd = click.prompt("Current Wallet Passphrase", hide_input=True)
                ctx.bitshares.wallet.unlock(pwd)
            else:
                click.echo("No wallet installed yet. Creating ...")
                pwd = click.prompt("Wallet Encryption Passphrase", hide_input=True, confirmation_prompt=True)
                ctx.bitshares.wallet.create(pwd)
        return ctx.invoke(f, *args, **kwargs)
    return update_wrapper(new_func, f)
main.py 文件源码 项目:service-level-reporting 作者: zalando-zmon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def set_config_file(config_file=DEFAULT_CONFIG_FILE):
    while True:
        url = click.prompt('Please enter the SLR base URL (e.g. https://slo-metrics.example.com)')

        with Action('Checking {}..'.format(url)):
            requests.get(url, timeout=5, allow_redirects=False)

        zmon_url = click.prompt('Please enter the ZMON URL (e.g. https://demo.zmon.io)')

        with Action('Checking {}..'.format(zmon_url)):
            requests.get(zmon_url, timeout=5, allow_redirects=False)
            break

    data = {
        'url': url,
        'zmon_url': zmon_url,
    }

    fn = os.path.expanduser(config_file)
    with Action('Writing configuration to {}..'.format(fn)):
        with open(fn, 'w') as fd:
            json.dump(data, fd)

    return data
index.py 文件源码 项目:bootcamp_cli 作者: jokamjohn 项目源码 文件源码 阅读 51 收藏 0 点赞 0 评论 0
def cli():
    # Show the user the intro message
    get_intro()

    # Prompt the user to enter a news source
    news_source = click.prompt("Please select a news source by entering its number or press enter for BBC", default=1)

    # Dictionary containing the news sources
    news_dict = get_news_sources()

    if news_source in news_dict.keys():
        get_news_articles(news_dict[news_source])
    else:
        click.echo(click.style("Wrong input try again", fg='red'))


# Return the news sources
sync.py 文件源码 项目:bc-7-Todo-Console-Application 作者: Onikah 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def upload_firebase(self):
        data={}
        category = []
        cat = session.query(Category).all()
        for x in cat:
            qry = session.query(Items).filter(Items.category_id==x.id)
            data[x.category]=[d.items for d in qry]

        name = click.prompt(click.style('Please enter your username:',  fg='cyan', bold=True))
        print Fore.GREEN  + 'Syncing..... '
        jsonData = firebase.put( '/todo-cli', name, data)
        if jsonData:
            print Fore.CYAN + 'Done!'
            exit()
        else:
            print 'Try again'
sync.py 文件源码 项目:bc-7-Todo-Console-Application 作者: Onikah 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def get_firebase(self):
        name = click.prompt(click.style('Please enter username?', fg = 'cyan' , bold=True))
        jsonData = firebase.get('/todo-cli' , name)
        for k in jsonData:
            #inserting category to database
            category = Category(category=k)
            session.add(category)
            session.commit()

            for i in jsonData[k]:
                s = select([Category])
                result = s.execute()
                for r in result:
                    if r[1] == k:
                        data = Items(category_id=r[0], items=i)
                        session.add(data)
                        session.commit()
                        session.close()

        click.secho('Done', fg = 'yellow' , bold=True)
todo.py 文件源码 项目:bc-7-Todo-Console-Application 作者: Onikah 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def start_todo():


    # click.echo(click.style("\n[1] Create new list of todo.", fg ='white', bold = True))
    # click.echo(click.style("[2] Add items to your category", fg ='white', bold = True))
    # click.echo(click.style("[q] Quit.", fg ='white', bold = True))

    choice = str(click.prompt(click.style('>>>',  fg = 'cyan', bold = True)))

    while choice != 'q':    
        # Respond to the user's choice.
        if 'create todo' in choice:
            print 'creating'
        elif 'open todo' in choice:
            print 'openning'
        elif 'list todo' in choice:
            print 'listing'
        elif choice:
            exit_todo()
        else:
            click.echo("\nTry again\n")



###LOOPING FUNCTIONS ###
todo.py 文件源码 项目:bc-7-Todo-Console-Application 作者: Onikah 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def open_todo(name):


    os.system('clear')

    todo_title()

    s = select([Category])
    result = s.execute()
    for r in result:
        if r[1] == name:
            q = session.query(Items).filter(Items.category_id==r[0]).all()
            click.secho(name.upper(), fg='cyan', bold=True, underline=True)
            for i in q:
                click.secho('>>>' + i.items, fg='white', bold=True )
        # else:
        #   click.secho('oops list {} doesnt exist'.format(name), fg='white', bold=True )

    item = click.prompt(click.style('>>',  fg='green', bold=True))
    if item == 'done':
        list_todo(name) 
    else:           
        add_todo(name, item)
add-node.py 文件源码 项目:openshift-ansible-contrib 作者: openshift 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def parse_cli_args(self):

        ''' Command line argument processing '''
        tag_help = '''Skip to various parts of install valid tags include:
        - vms (create vms for adding nodes to cluster or CNS/CRS)
        - node-setup (install the proper packages on the CNS/CRS nodes)
        - heketi-setup (install heketi and config on the crs master/CRS ONLY)
        - heketi-ocp (install the heketi secret and storage class on OCP/CRS ONLY)
        - clean (remove vms and unregister them from RHN also remove storage classes or secrets'''
        parser = argparse.ArgumentParser(description='Add new nodes to an existing OCP deployment', formatter_class=RawTextHelpFormatter)
        parser.add_argument('--node_type', action='store', default='app', help='Specify the node label: app, infra, storage')
        parser.add_argument('--node_number', action='store', default='1', help='Specify the number of nodes to add')
        parser.add_argument('--create_inventory', action='store_true', help='Helper script to create json inventory file and exit')
        parser.add_argument('--no_confirm', default=None, help='Skip confirmation prompt')
        parser.add_argument('--tag', default=None, help=tag_help)
        parser.add_argument('--verbose', default=None, action='store_true', help='Verbosely display commands')
        self.args = parser.parse_args()
        self.verbose = self.args.verbose
add-node.py 文件源码 项目:openshift-ansible 作者: nearform 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def parse_cli_args(self):

        ''' Command line argument processing '''
        tag_help = '''Skip to various parts of install valid tags include:
        - vms (create vms for adding nodes to cluster or CNS/CRS)
        - node-setup (install the proper packages on the CNS/CRS nodes)
        - heketi-setup (install heketi and config on the crs master/CRS ONLY)
        - heketi-ocp (install the heketi secret and storage class on OCP/CRS ONLY)
        - clean (remove vms and unregister them from RHN also remove storage classes or secrets'''
        parser = argparse.ArgumentParser(description='Add new nodes to an existing OCP deployment', formatter_class=RawTextHelpFormatter)
        parser.add_argument('--node_type', action='store', default='app', help='Specify the node label: app, infra, storage')
        parser.add_argument('--node_number', action='store', default='1', help='Specify the number of nodes to add')
        parser.add_argument('--create_inventory', action='store_true', help='Helper script to create json inventory file and exit')
        parser.add_argument('--no_confirm', default=None, help='Skip confirmation prompt')
        parser.add_argument('--tag', default=None, help=tag_help)
        parser.add_argument('--verbose', default=None, action='store_true', help='Verbosely display commands')
        self.args = parser.parse_args()
        self.verbose = self.args.verbose
utils.py 文件源码 项目:netease-dl 作者: ziwenxie 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def select_one_song(songs):
        """Display the songs returned by search api.

        :params songs: API['result']['songs']
        :return: a Song object.
        """

        if len(songs) == 1:
            select_i = 0
        else:
            table = PrettyTable(['Sequence', 'Song Name', 'Artist Name'])
            for i, song in enumerate(songs, 1):
                table.add_row([i, song['name'], song['ar'][0]['name']])
            click.echo(table)

            select_i = click.prompt('Select one song', type=int, default=1)
            while select_i < 1 or select_i > len(songs):
                select_i = click.prompt('Error Select! Select Again', type=int)

        song_id, song_name = songs[select_i-1]['id'], songs[select_i-1]['name']
        song = Song(song_id, song_name)
        return song
utils.py 文件源码 项目:netease-dl 作者: ziwenxie 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def select_one_album(albums):
        """Display the albums returned by search api.

        :params albums: API['result']['albums']
        :return: a Album object.
        """

        if len(albums) == 1:
            select_i = 0
        else:
            table = PrettyTable(['Sequence', 'Album Name', 'Artist Name'])
            for i, album in enumerate(albums, 1):
                table.add_row([i, album['name'], album['artist']['name']])
            click.echo(table)

            select_i = click.prompt('Select one album', type=int, default=1)
            while select_i < 1 or select_i > len(albums):
                select_i = click.prompt('Error Select! Select Again', type=int)

        album_id = albums[select_i-1]['id']
        album_name = albums[select_i-1]['name']
        album = Album(album_id, album_name)
        return album
utils.py 文件源码 项目:netease-dl 作者: ziwenxie 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def select_one_artist(artists):
        """Display the artists returned by search api.

        :params artists: API['result']['artists']
        :return: a Artist object.
        """

        if len(artists) == 1:
            select_i = 0
        else:
            table = PrettyTable(['Sequence', 'Artist Name'])
            for i, artist in enumerate(artists, 1):
                table.add_row([i, artist['name']])
            click.echo(table)

            select_i = click.prompt('Select one artist', type=int, default=1)
            while select_i < 1 or select_i > len(artists):
                select_i = click.prompt('Error Select! Select Again', type=int)

        artist_id = artists[select_i-1]['id']
        artist_name = artists[select_i-1]['name']
        artist = Artist(artist_id, artist_name)
        return artist
utils.py 文件源码 项目:netease-dl 作者: ziwenxie 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def select_one_playlist(playlists):
        """Display the playlists returned by search api or user playlist.

        :params playlists: API['result']['playlists'] or API['playlist']
        :return: a Playlist object.
        """

        if len(playlists) == 1:
            select_i = 0
        else:
            table = PrettyTable(['Sequence', 'Name'])
            for i, playlist in enumerate(playlists, 1):
                table.add_row([i, playlist['name']])
            click.echo(table)

            select_i = click.prompt('Select one playlist', type=int, default=1)
            while select_i < 1 or select_i > len(playlists):
                select_i = click.prompt('Error Select! Select Again', type=int)

        playlist_id = playlists[select_i-1]['id']
        playlist_name = playlists[select_i-1]['name']
        playlist = Playlist(playlist_id, playlist_name)
        return playlist
utils.py 文件源码 项目:netease-dl 作者: ziwenxie 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def select_one_user(users):
        """Display the users returned by search api.

        :params users: API['result']['userprofiles']
        :return: a User object.
        """

        if len(users) == 1:
            select_i = 0
        else:
            table = PrettyTable(['Sequence', 'Name'])
            for i, user in enumerate(users, 1):
                table.add_row([i, user['nickname']])
            click.echo(table)

            select_i = click.prompt('Select one user', type=int, default=1)
            while select_i < 1 or select_i > len(users):
                select_i = click.prompt('Error Select! Select Again', type=int)

        user_id = users[select_i-1]['userId']
        user_name = users[select_i-1]['nickname']
        user = User(user_id, user_name)
        return user
friday.py 文件源码 项目:Friday 作者: Zenohm 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def listen(self):
        # Default value.
        # TODO: Input plugin system goes here
        # Plugins should be used for getting input so users can build their
        # own custom front-end to the application.
        # This will allow the speech to text functions to be moved out of the
        # main class and into their own plugins.
        if self.input_system == 'google':
            self.question = self._google_stt()
        else:
            self.question = click.prompt("Input your query")

        # TODO: Loading plugin system goes here
        # Eventually I want people to be able to build custom behavior
        # that executes when the response is being fetched. So there could
        # be a loading screen that plays music or something for example.
        click.echo("Wait for response...")
        # Get a response from the AI using the api interface.
        self.ai.get_response(self.question)
        # Clean up the response and turn it into a Python object that can be read
        self.response = self.ai.parse()
        return self.response
account.py 文件源码 项目:python-decent 作者: aaroncox 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def allow(ctx, foreign_account, permission, weight, threshold, account):
    """ Add a key/account to an account's permission
    """
    if not foreign_account:
        from decentbase.account import PasswordKey
        pwd = click.prompt(
            "Password for Key Derivation",
            hide_input=True,
            confirmation_prompt=True
        )
        foreign_account = format(
            PasswordKey(account, pwd, permission).get_public(),
            "DCT"
        )
    pprint(ctx.decent.allow(
        foreign_account,
        weight=weight,
        account=account,
        permission=permission,
        threshold=threshold
    ))
decorators.py 文件源码 项目:python-decent 作者: aaroncox 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def unlockWallet(f):
    @click.pass_context
    def new_func(ctx, *args, **kwargs):
        if not ctx.obj.get("unsigned", False):
            if ctx.decent.wallet.created():
                if "UNLOCK" in os.environ:
                    pwd = os.environ["UNLOCK"]
                else:
                    pwd = click.prompt("Current Wallet Passphrase", hide_input=True)
                ctx.decent.wallet.unlock(pwd)
            else:
                click.echo("No wallet installed yet. Creating ...")
                pwd = click.prompt("Wallet Encryption Passphrase", hide_input=True, confirmation_prompt=True)
                ctx.decent.wallet.create(pwd)
        return ctx.invoke(f, *args, **kwargs)
    return update_wrapper(new_func, f)
__init__.py 文件源码 项目:kyber 作者: TakumiHQ 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def init_app():
    """ create a new app, or sync with an existing one """
    cwd = os.path.abspath('.')

    try:
        repo = git.Repo.discover(cwd)
    except NotGitRepository:
        click.echo("No repository found")
        sys.exit(1)

    suggested_name = init.get_default_name(cwd)
    if suggested_name is None:
        click.echo("Unable to derive a name from the current git repository or directory!")
        sys.exit(2)

    name = click.prompt("Enter environment name".format(suggested_name), default=suggested_name)

    init.initialize(name, repo.head())
start.py 文件源码 项目:pyFootball 作者: JustnAugr 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def main():
    """pyFootball v.1 Early Alpha

    A python based football management simulator,
    very similar to and heavily based on Football Manager created by Sports
    Interactive.

    To start or load a game, run this file without any parameters.

    Coded by Justin Auger
    http://justnaugr.github.io\n
    Credits to Click for the great CLI.

    """
    start = click.prompt('Would you like to start a new game or load a saved game?', type=click.Choice(['new','load']))
    if start=='new':
        new_game()
    elif start=='load':
        load_game()
cli.py 文件源码 项目:ngage 作者: 20c 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def connect(self, kwargs):
        try:
            # get config
            config = self.get_connect_config(kwargs)

            typ = config['type']
            # check for subtype
            if ':' in typ:
                typ = config['type'].split(':', 1)[0]

            cls = ngage.plugin.get_plugin_class(typ)
            drv = cls(config)
            self.log.debug("connecting to {host}".format(**config))
            drv.open()
            return drv

        except AuthenticationError:
            config['password'] = click.prompt('password', hide_input=True)
            if config['password']:
                return connect(config)
            raise


问题


面经


文章

微信
公众号

扫码关注公众号