Python PyInquirer.prompt() Examples

The following are 22 code examples of PyInquirer.prompt(). 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 PyInquirer , or try the search function .
Example #1
Source File: cliq.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def command(help: str) -> Callable[[Callable], Callable]:
    def decorator(func) -> Callable:
        questions = func.__inquirer_questions__.copy()

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for key, value in kwargs.items():
                if key not in questions:
                    continue
                if value is not None and (questions[key]["type"] != "confirm" or value != "null"):
                    questions.pop(key, None)
            question_list = list(questions.values())
            question_list.reverse()
            resp = prompt(question_list, keyboard_interrupt_msg="Aborted!")
            if not resp and question_list:
                return
            kwargs = {**kwargs, **resp}
            func(*args, **kwargs)

        return app.command(help=help)(wrapper)

    return decorator 
Example #2
Source File: build.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def read_output_path(output: str, meta: PluginMeta) -> Optional[str]:
    directory = os.getcwd()
    filename = f"{meta.id}-v{meta.version}.mbp"
    if not output:
        output = os.path.join(directory, filename)
    elif os.path.isdir(output):
        output = os.path.join(output, filename)
    elif os.path.exists(output):
        override = prompt({
            "type": "confirm",
            "name": "override",
            "message": f"{output} exists, override?"
        })["override"]
        if not override:
            return None
        os.remove(output)
    return os.path.abspath(output) 
Example #3
Source File: start.py    From lightnovel-crawler with Apache License 2.0 6 votes vote down vote up
def open_folder(self):
    args = get_args()

    if args.suppress:
        return False
    # end if

    answer = prompt([
        {
            'type': 'confirm',
            'name': 'exit',
            'message': 'Open the output folder?',
            'default': True,
        },
    ])

    return answer['exit']
# end def 
Example #4
Source File: output_style.py    From lightnovel-crawler with Apache License 2.0 6 votes vote down vote up
def get_output_formats(self):
    '''Returns a dictionary of output formats.'''
    args = get_args()

    formats = args.output_formats
    if not (formats or args.suppress):
        answer = prompt([
            {
                'type': 'checkbox',
                'name': 'formats',
                'message': 'Which output formats to create?',
                'choices': [{'name': x, 'checked': x == 'epub'} for x in available_formats],
            },
        ])
        formats = answer['formats']
    # end if

    if not formats or len(formats) == 0:
        formats = ['epub']  # default to epub if none selected
    # end if

    return {x: (x in formats) for x in available_formats}
# end def 
Example #5
Source File: commands.py    From grapheneX with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, document):
        """Validate the namespace for the prompt"""

        namespaces = get_forbidden_namespaces()
        if document.text.lower() in [namespace.lower() for namespace in namespaces]:
            raise ValidationError(
                    message="You do not have permission to access this namespace.",
                    cursor_position=len(document.text)) 
Example #6
Source File: commands.py    From grapheneX with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, document):
            """Validate the module name for the prompt"""

            if not re.match(r'^\w+$', document.text):
                raise ValidationError(
                    message='Enter a valid module name',
                    cursor_position=len(document.text))
            elif document.text.lower() in [module.lower() for module in self.modules]:
                raise ValidationError(
                    message="Try a different name, this module name is not available.",
                    cursor_position=len(document.text)) 
Example #7
Source File: tag.py    From harley_the_bot with Apache License 2.0 5 votes vote down vote up
def loadtweets():
    while True:
        tweets = datadb.load_data_for_tag();
        for tweet in tweets:
            print(tweet[3] +" \t" + tweet[0])
            answers = prompt(questions)
            if answers["tag"]=="exit":
                sys.exit()
            print("set tags:"+str(tweet[0])+" to "+str(answers["tag"]))
            datadb.tag_data(tweet[0], answers["tag"], by_user_id) 
Example #8
Source File: range_selection.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def get_range_from_chapters(self, times=0):
    '''Returns a range created using individual chapters'''
    selected = None
    args = get_args()

    if times == 0 and not selected:
        selected = get_args().chapters
    # end if

    if not selected and args.suppress:
        selected = self.app.crawler.chapters
    # end if

    if not selected:
        answer = prompt([
            {
                'type': 'checkbox',
                'name': 'chapters',
                'message': 'Choose chapters to download:',
                'choices': [
                    {'name': '%d - %s' % (chap['id'], chap['title'])}
                    for chap in self.app.crawler.chapters
                ],
                'validate': lambda ans: True if len(ans) > 0
                else 'You must choose at least one chapter.',
            }
        ])
        selected = [
            int(val.split(' ')[0])
            for val in answer['chapters']
        ]
    else:
        selected = [
            self.app.crawler.get_chapter_index_of(x)
            for x in selected if x
        ]
    # end if

    if times < 3 and len(selected) == 0:
        return self.get_range_from_chapters(times + 1)
    # end if

    selected = [
        x for x in selected
        if 1 <= x <= len(self.app.crawler.chapters)
    ]

    return selected
# end def 
Example #9
Source File: range_selection.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def get_range_from_volumes(self, times=0):
    '''Returns a range created using volume list'''
    selected = None
    args = get_args()

    if times == 0 and args.volumes:
        selected = [int(x) for x in args.volumes]
    # end if

    if not selected and args.suppress:
        selected = [x['id'] for x in self.app.crawler.volumes]
    # end if

    if not selected:
        answer = prompt([
            {
                'type': 'checkbox',
                'name': 'volumes',
                'message': 'Choose volumes to download:',
                'choices': [
                    {
                        'name': '%d - %s (Chapter %d-%d) [%d chapters]' % (
                            vol['id'], vol['title'], vol['start_chapter'],
                            vol['final_chapter'], vol['chapter_count'])
                    }
                    for vol in self.app.crawler.volumes
                ],
                'validate': lambda ans: True if len(ans) > 0
                else 'You must choose at least one volume.'
            }
        ])
        selected = [int(val.split(' ')[0]) for val in answer['volumes']]
    # end if

    if times < 3 and len(selected) == 0:
        return self.get_range_from_volumes(times + 1)
    # end if

    return selected
# end def 
Example #10
Source File: get_crawler.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def get_novel_url(self):
    '''Returns a novel page url or a query'''
    args = get_args()
    if args.query and len(args.query) > 1:
        return args.query
    # end if

    url = args.novel_page
    if url:
        if re.match(r'^https?://.+\..+$', url):
            return url
        else:
            raise Exception('Invalid URL of novel page')
        # end if
    # end if

    try:
        if args.suppress:
            raise Exception()
        # end if

        answer = prompt([
            {
                'type': 'input',
                'name': 'novel',
                'message': 'Enter novel page url or query novel:',
                'validate': lambda val: 'Input should not be empty'
                if len(val) == 0 else True,
            },
        ])
        return answer['novel'].strip()
    except Exception:
        raise Exception('Novel page url or query was not given')
    # end try
# end def 
Example #11
Source File: output_style.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def should_pack_by_volume(self):
    '''Returns whether to generate single or multiple files by volumes'''
    args = get_args()

    if args.single:
        return False
    elif args.multi:
        return True
    # end if

    if args.suppress:
        return False
    # end if

    # answer = prompt([
    #     {
    #         'type': 'confirm',
    #         'name': 'volume',
    #         'message': 'Split file by volumes?',
    #         'default': False,
    #     },
    # ])
    # return answer['volume']

    answer = prompt([
        {
            'type': 'list',
            'name': 'split',
            'message': 'How many files to generate?',
            'choices': [
                'Pack everything into a single file',
                'Split by volume into multiple files'
            ],
        },
    ])
    return answer['split'].startswith('Split')
# end def 
Example #12
Source File: output_style.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def force_replace_old(self):
    args = get_args()

    if args.force:
        return True
    elif args.ignore:
        return False
    # end if

    if args.suppress:
        return False
    # end if

    # answer = prompt([
    #     {
    #         'type': 'confirm',
    #         'name': 'force',
    #         'message': 'Detected existing folder. Replace it?',
    #         'default': False,
    #     },
    # ])
    # return answer['force']

    answer = prompt([
        {
            'type': 'list',
            'name': 'replace',
            'message': 'What to do with existing folder?',
            'choices': [
                'Remove old folder and start fresh',
                'Download remaining chapters only',
            ],
        },
    ])
    return answer['replace'].startswith('Remove')
# end def 
Example #13
Source File: output_style.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def get_output_path(self):
    '''Returns a valid output path where the files are stored'''
    args = get_args()
    output_path = args.output_path

    if args.suppress:
        if not output_path:
            output_path = self.app.output_path
        # end if
        if not output_path:
            output_path = os.path.join('Lightnovels', 'Unknown Novel')
        # end if
    # end if

    if not output_path:
        answer = prompt([
            {
                'type': 'input',
                'name': 'output',
                'message': 'Enter output direcotry:',
                'default': os.path.abspath(self.app.output_path),
            },
        ])
        output_path = answer['output']
    # end if

    output_path = os.path.abspath(output_path)
    if os.path.exists(output_path):
        if self.force_replace_old():
            shutil.rmtree(output_path, ignore_errors=True)
        # end if
    # end if
    os.makedirs(output_path, exist_ok=True)

    return output_path
# end def 
Example #14
Source File: dockerize.py    From fetchy with MIT License 5 votes vote down vote up
def _validate_configuration(self, configuration):
        if not is_os_supported(configuration["distribution"]):
            message = (
                "Sorry, currently we do not support packages indices that are "
                "running on your current operating system. Please select an operating system "
                "you'd like to use to search packages for:"
            )
            configuration["distribution"] = prompt(
                [
                    {
                        "type": "list",
                        "message": message,
                        "name": "distribution",
                        "choices": ["ubuntu", "debian"],
                    }
                ]
            )["distribution"]
        if not is_version_supported(
            configuration["distribution"], configuration["codename"]
        ):
            message = (
                f"Sorry, the codename '{configuration['codename']}' is not recognised by fetchy for "
                f"the distribution {configuration['distribution']}. Please select a codename for which "
                "you'd like to search packages for:"
            )
            configuration["codename"] = prompt(
                [
                    {
                        "type": "list",
                        "message": message,
                        "name": "codename",
                        "choices": get_supported_versions_for(
                            configuration["distribution"]
                        ),
                    }
                ]
            )["codename"] 
Example #15
Source File: hierarchical.py    From PyInquirer with MIT License 5 votes vote down vote up
def encounter2b():
    prompt({
        'type': 'list',
        'name': 'weapon',
        'message': 'Pick one',
        'choices': [
            'Use the stick',
            'Grab a large rock',
            'Try and make a run for it',
            'Attack the wolf unarmed'
        ]
    }, style=custom_style_2)
    print('The wolf mauls you. You die. The end.') 
Example #16
Source File: hierarchical.py    From PyInquirer with MIT License 5 votes vote down vote up
def ask_direction():
    directions_prompt = {
        'type': 'list',
        'name': 'direction',
        'message': 'Which direction would you like to go?',
        'choices': ['Forward', 'Right', 'Left', 'Back']
    }
    answers = prompt(directions_prompt)
    return answers['direction']

# TODO better to use while loop than recursion! 
Example #17
Source File: cliq.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def option(short: str, long: str, message: str = None, help: str = None,
           click_type: Union[str, Callable[[str], Any]] = None, inq_type: str = None,
           validator: Validator = None, required: bool = False, default: str = None,
           is_flag: bool = False, prompt: bool = True) -> Callable[[Callable], Callable]:
    if not message:
        message = long[2].upper() + long[3:]
    click_type = validator.click_type if isinstance(validator, ClickValidator) else click_type
    if is_flag:
        click_type = yesno

    def decorator(func) -> Callable:
        click.option(short, long, help=help, type=click_type)(func)
        if not prompt:
            return func
        if not hasattr(func, "__inquirer_questions__"):
            func.__inquirer_questions__ = {}
        q = {
            "type": (inq_type if isinstance(inq_type, str)
                     else ("input" if not is_flag
                           else "confirm")),
            "name": long[2:],
            "message": message,
        }
        if default is not None:
            q["default"] = default
        if required:
            q["validator"] = Required(validator)
        elif validator:
            q["validator"] = validator
        func.__inquirer_questions__[long[2:]] = q
        return func

    return decorator 
Example #18
Source File: get_crawler.py    From lightnovel-crawler with Apache License 2.0 4 votes vote down vote up
def choose_a_novel(self):
    '''Choose a single novel url from the search result'''
    args = get_args()

    # Choose a novel title
    choices = self.app.search_results
    selected_choice = self.app.search_results[0]
    if len(choices) > 1 and not args.suppress:
        answer = prompt([
            {
                'type': 'list',
                'name': 'novel',
                'message': 'Which one is your novel?',
                'choices': display.format_novel_choices(choices),
            }
        ])

        index = int(answer['novel'].split('.')[0])
        selected_choice = self.app.search_results[index - 1]
    # end if

    # Choose the novel source
    novels = selected_choice['novels']
    selected_novel = novels[0]
    if len(novels) > 1 and not args.suppress:
        answer = prompt([
            {
                'type': 'list',
                'name': 'novel',
                'message': 'Choose a source to download?',
                'choices': ['0. Back'] + display.format_source_choices(novels),
            }
        ])

        index = int(answer['novel'].split('.')[0])
        if index == 0:
            return self.choose_a_novel()
        # end if
        selected_novel = novels[index - 1]
    # end if

    return selected_novel['url']
# end def 
Example #19
Source File: start.py    From lightnovel-crawler with Apache License 2.0 4 votes vote down vote up
def process_chapter_range(self):
    chapters = []
    res = self.get_range_selection()

    args = get_args()
    if res == 'all':
        chapters = self.app.crawler.chapters[:]
    elif res == 'first':
        n = args.first or 10
        chapters = self.app.crawler.chapters[:n]
    elif res == 'last':
        n = args.last or 10
        chapters = self.app.crawler.chapters[-n:]
    elif res == 'page':
        start, stop = self.get_range_using_urls()
        chapters = self.app.crawler.chapters[start:(stop + 1)]
    elif res == 'range':
        start, stop = self.get_range_using_index()
        chapters = self.app.crawler.chapters[start:(stop + 1)]
    elif res == 'volumes':
        selected = self.get_range_from_volumes()
        chapters = [
            chap for chap in self.app.crawler.chapters
            if selected.count(chap['volume']) > 0
        ]
    elif res == 'chapters':
        selected = self.get_range_from_chapters()
        chapters = [
            chap for chap in self.app.crawler.chapters
            if selected.count(chap['id']) > 0
        ]
    # end if

    if len(chapters) == 0:
        raise Exception('No chapters to download')
    # end if

    self.log.debug('Selected chapters:')
    self.log.debug(chapters)
    if not args.suppress:
        answer = prompt([
            {
                'type': 'list',
                'name': 'continue',
                'message': '%d chapters selected' % len(chapters),
                'choices': [
                    'Continue',
                    'Change selection'
                ],
            }
        ])
        if answer['continue'] == 'Change selection':
            return self.process_chapter_range()
        # end if
    # end if

    self.log.info('%d chapters to be downloaded', len(chapters))
    return chapters
# end def 
Example #20
Source File: login_info.py    From lightnovel-crawler with Apache License 2.0 4 votes vote down vote up
def get_login_info(self):
    '''Returns the (email, password) pair for login'''
    args = get_args()

    if args.login:
        return args.login
    # end if

    if args.suppress:
        return False
    # end if

    answer = prompt([
        {
            'type': 'confirm',
            'name': 'login',
            'message': 'Do you want to log in?',
            'default': False
        },
    ])

    if answer['login']:
        answer = prompt([
            {
                'type': 'input',
                'name': 'email',
                'message': 'Username/Email:',
                'validate': lambda val: True if len(val)
                else 'Email address should be not be empty'
            },
            {
                'type': 'password',
                'name': 'password',
                'message': 'Password:',
                'validate': lambda val: True if len(val)
                else 'Password should be not be empty'
            },
        ])
        return answer['email'], answer['password']
    # end if

    return None
# end if 
Example #21
Source File: range_selection.py    From lightnovel-crawler with Apache License 2.0 4 votes vote down vote up
def get_range_selection(self):
    '''
    Returns a choice of how to select the range of chapters to downloads
    '''
    volume_count = len(self.app.crawler.volumes)
    chapter_count = len(self.app.crawler.chapters)
    selections = ['all', 'last', 'first',
                  'page', 'range', 'volumes', 'chapters']

    args = get_args()
    for key in selections:
        if args.__getattribute__(key):
            return key
        # end if
    # end if

    if args.suppress:
        return selections[0]
    # end if

    big_list_warn = '(warn: very big list)' if chapter_count > 50 else ''

    choices = [
        'Everything! (%d chapters)' % chapter_count,
        'Last 10 chapters',
        'First 10 chapters',
        'Custom range using URL',
        'Custom range using index',
        'Select specific volumes (%d volumes)' % volume_count,
        'Select specific chapters ' + big_list_warn,
    ]
    if chapter_count <= 20:
        choices.pop(1)
        choices.pop(1)
    # end if

    answer = prompt([
        {
            'type': 'list',
            'name': 'choice',
            'message': 'Which chapters to download?',
            'choices': choices,
        },
    ])

    return selections[choices.index(answer['choice'])]
# end def 
Example #22
Source File: range_selection.py    From lightnovel-crawler with Apache License 2.0 4 votes vote down vote up
def get_range_using_index(self):
    '''Returns a range selected using chapter indices'''
    chapter_count = len(self.app.crawler.chapters)

    args = get_args()
    start, stop = args.range or (None, None)

    if args.suppress and not (start and stop):
        return (0, chapter_count - 1)
    # end if

    if not (start and stop):
        def validator(val):
            try:
                if 1 <= int(val) <= chapter_count:
                    return True
            except Exception:
                pass
            return 'Enter an integer between 1 and %d' % chapter_count
        # end def
        answer = prompt([
            {
                'type': 'input',
                'name': 'start',
                'message': 'Enter start index (1 to %d):' % chapter_count,
                'validate': validator,
                'filter': lambda val: int(val),
            },
            {
                'type': 'input',
                'name': 'stop',
                'message': 'Enter final index (1 to %d):' % chapter_count,
                'validate': validator,
                'filter': lambda val: int(val),
            },
        ])
        start = answer['start'] - 1
        stop = answer['stop'] - 1
    else:
        start = start - 1
        stop = stop - 1
    # end if

    return (start, stop) if start < stop else (stop, start)
# end def