Prompt user for information

Examples

A simple prompt

import sy.prompt

# Ask a yes or no question
yes = sy.prompt.confirm('Do you want to add a mailserver? [y/n]: ')

if not yes:
    print 'I know you want one!'
print

# Mailserver choices
mailservers = ['sendmail', 'postfix', 'qmail']

# Let the user choose a mailserver
selected = sy.prompt.choose('  Which mailserver do you want?', mailservers)
mailserver = mailservers[selected]

if mailserver == 'sendmail':
    usesendmail = sy.prompt.confirm(
                      '    Do you really want to use sendmail? [y/N]: ',
                      default=False)
    if not usesendmail:
        import sys
        sys.exit(0)

# Get a number
mailsperhour = sy.prompt.ask('  How many mails are you expecting per hour?: ',
                             type=int) 

# Check the response
domainname = sy.prompt.ask('  Whats you domainname?: ', checks=[
                            ('^\w+\.\w+$', 'Enter a domain like foo.com')])
print
print 'Ok, setting up', mailserver, 'on', domainname, 'expecting %d m/h' % mailsperhour

This would result in sessions like this:

Do you want to add a mailserver? [y/n]: n
I know you want one!

  Which mailserver do you want?
  1) sendmail
  2) postfix
  3) qmail

  Choice: first
  You must use numbers
  Choice: 1
    Do you really want to use sendmail? [y/N]: q
    Answer yes or no
    Do you really want to use sendmail? [y/N]: y
  How many mails are you expecting per hour?: a lot!
  Answer must be a integer
  How many mails are you expecting per hour?: 5
  Whats you domainname?: foo,com
  Enter a domain like foo.com
  Whats you domainname?: foo.com

Ok, setting up sendmail on foo.com expecting 5 m/h

Question and their errorresponses can be indented which makes us able to create nicer nested prompts.

sy.prompt content

synopsis:Prompt users for information
sy.prompt.ask(question, default='', type=None, checks=())

Ask user a question

Parameters:
  • question – Question to prompt for. Leading spaces will set the indent level for the error responses.
  • default – The default answer as a string.
  • type

    Python type the answer must have. Answers are converted to the requested type before checks are run. Support for str, int, float and bool are built in.

    If you supply your own function it must take a string as argument and return a tuple where the first value is the converted answer or None if if failed. If it fails the second value is the error message displayd to the user, example:

    def int_list(answer):
        try:
            ints = [int(i) for i in answer.split(',')]
            # Success!
            return ints, None
        except ValueError: 
            # Fail!
            return None, 'You must supply a list of integers'
    
    sy.prompt.ask('Give me a intlist: ', type=int_list)
    
    Give me a intlist: 1, 2, 3
    [1, 2, 3]
  • checks – List of checks in the form [(check, errormsg), (check, ...)]. The check can be a regular expression string, a compiled pattern or a function. The function must take a string as argument and return True if the check passes. If the check fails the errormsg is printed to the user.
sy.prompt.choose(question, choices, multichoice=False, default='')

Let user select one or more items from a list

Presents user with the question and the list of choices. Returns the index of the choice selected. If multichoice is true the user can pick more then one choice and a list of indexes are returned:

choice = sy.prompt.choose('Pick one:', ['a', 'b', 'c'])
# Pick one:
#  1) a
#  2) b
#  3) c
# Choice: 1

print choice
0

choices = sy.prompt.choose('Pick one or more:', ['a', 'b', 'c'], 
                            mutlichoice=True)
# Pick one or more:
#  1) a
#  2) b
#  3) c
# Choices: 1, 3

print choices
[0,2]
Parameters:
  • question – Question to print before list of choices
  • choices – List of choices. If the choice is not a string an attempt to convert it to a string with str() is made.
  • multichoice – If True the user can pick multiple choices, separated by commas. The return value will be a list of indexes in the choices list that the user picked.
  • default – Default choice as a string the user would have written, ex: "1,2".
sy.prompt.confirm(question, default='')

Ask a yes or no question

Parameters:
  • default – True or False
Returns:

Boolean answer

Table Of Contents

Previous topic

Running commands

Next topic

Utilities & Logging

This Page