11"""
22
33Copyright (C) 2020-2022 Vanessa Sochat.
4+ 2024 Yaroslav O. Halchenko
45
56This Source Code Form is subject to the terms of the
67Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed
78with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
89
910"""
1011
11-
12- enter_input = getattr (__builtins__ , "raw_input" , input )
13-
14-
15- def request_input ():
16- """Wait for the user to input some string, optionally with multiple lines."""
17- lines = []
18-
19- # The message can be multiple lines
20- while True :
21- try :
22- line = enter_input ()
23- except EOFError :
24- break
25- if line :
26- lines .append (line )
27-
28- return "\n " .join (lines )
12+ import re
2913
3014
3115def choice_prompt (prompt , choices , choice_prefix = None , multiple = False ):
@@ -41,15 +25,12 @@ def choice_prompt(prompt, choices, choice_prefix=None, multiple=False):
4125 choice = None
4226 print (prompt )
4327
44- # Support for Python 2 (raw_input)
45- get_input = getattr (__builtins__ , "raw_input" , input )
46-
4728 if not choice_prefix :
4829 choice_prefix = "/" .join (choices )
4930 message = "[%s] : " % (choice_prefix )
5031
5132 while choice not in choices :
52- choice = get_input (message ).strip ()
33+ choice = input (message ).strip ()
5334
5435 # If multiple allowed, add selection to choices if includes all valid
5536 if multiple is True :
@@ -58,3 +39,22 @@ def choice_prompt(prompt, choices, choice_prefix=None, multiple=False):
5839 choices .append (choice )
5940 message = "Please enter a valid option in [%s]" % choice_prefix
6041 return choice
42+
43+
44+ def entry_prompt (prompt , regex = None ):
45+ """Ask the user for a prompt, and only return when a valid entry is provided.
46+
47+ Parameters
48+ ==========
49+ prompt: the prompt to ask the user
50+ regex: a regular expression to match the entry
51+ """
52+ entry = None
53+ print (prompt )
54+ message = "Please enter a value. Empty to skip: "
55+ while not entry :
56+ entry = input (message ).strip ()
57+ if entry and regex is not None and not re .match (regex , entry ):
58+ entry = None
59+ message = r"Please enter a valid response. Should match regex {regex!r}"
60+ return entry
0 commit comments