def pager(text, pagesize=None):
"""
Paging output, mimic external command less/more
"""
if not pagesize:
pagesize = config.Option.get("pagesize")
if pagesize <= 0:
msg(text)
return
i = 1
text = text.splitlines()
l = len(text)
for line in text:
msg(line)
if i % pagesize == 0:
ans = input("--More--(%d/%d)" % (i, l))
if ans.lower().strip() == "q":
break
i += 1
return
python类input()的实例源码
def user_input(self, prompt=None):
"""
A wrapper function for getting user input while keeping track of the amount of time spent
waiting for it.
"""
start = arrow.utcnow()
try:
if self.default_format and prompt:
return raw_input('%(format)s%(prompt)s%(end)s' % {
'format': self.default_format,
'prompt': prompt,
'end': TerminalFormats.ENDC
})
else:
return raw_input(prompt)
finally:
end = arrow.utcnow()
self._waiting_on_user_delta += end - start
def handle(self, config, email, password, target, name, **options):
try:
config.get('serverapi', 'server_id')
except NoOptionError:
pass
else:
raise CommandError("This server is already registered. If you've unregistered it from your team dashboard, you can delete {}".format(options['config_path']))
if email is None:
email = input("Enter your Cloak email: ")
if password is None:
password = getpass("Enter your Cloak password: ")
if target is None:
target = input("Enter the target identifier (from the team dashboard): ")
server = Server.register(email, password, target, name)
config.set('serverapi', 'server_id', server.server_id)
config.set('serverapi', 'auth_token', server.auth_token)
print("This server has been registered. The next step is to request a certificate.", file=self.stdout)
def ask_for_domain():
"""
Prompt the user for a Canvas domain.
To ensure that the API calls are made on an encrypted SSL connection the initial 'https://' is pre-specified.
To ensure that the user input is 1) a valid URL and 2) a URL representing a Canvas web server request is used
to fetch a resources on the Canvas page. If the GET requests fails the URL was not valid. If the server returns
a 404 unauthenticated error the domain is very likely to be a Canvas server, if anything else is returned the
URL points to a correct URL that is not a Canvas server.
"""
found = False
# Keep asking until a valid domain has been entered by the user
while not found:
domain = u"https://" + input(u"\nEnter the Canvas domain of your institution:\n$ https://")
found = static_functions.validate_domain(domain)
return domain
def ask_for_advanced_settings(settings):
choice = -1
while choice not in (1, 2):
settings.print_settings(clear=True)
print(ANSI.format(u"\n\nAll mandatory settings are set. Do you wish see advanced settings?",
u"announcer"))
print(ANSI.format(u"\n[1]\tShow advanced settings (recommended)", u"bold"))
print(ANSI.format(u"[2]\tUse default settings", u"bold"))
try:
choice = int(input(u"\nChoose number: "))
except ValueError:
continue
if choice == 1:
return True
elif choice == 2:
return False
else:
continue
def ask_for_assignment_sync(settings):
choice = -1
while choice not in (1, 2):
settings.print_advanced_settings(clear=True)
print(ANSI.format(u"\n\nAssignments settings", u"announcer"))
print(ANSI.format(u"Would you like CanvasSync to synchronize assignments?\n\n"
u"The assignment description will be downloaded as a HTML to be viewed offline\n"
u"and files hosted on the Canvas server that are described in the assignment\n"
u"description section will be downloaded to the same folder.\n", u"white"))
print(ANSI.format(u"1) Sync assignments (default)", u"bold"))
print(ANSI.format(u"2) Do not sync assignments", u"bold"))
try:
choice = int(input(u"\nChoose number: "))
except ValueError:
continue
if choice == 1:
return True
elif choice == 2:
return False
else:
continue
def main_menu(settings):
"""
Main menu function, calss the settings.show_
main_screen function and handles user response
"""
to_do = settings.show_main_screen(settings.settings_file_exists())
# Act according to the users input to the main menu function
if to_do == u"quit":
sys.exit()
elif to_do == u"set_settings":
settings.set_settings()
main_menu(settings)
elif to_do == u"show_settings":
settings.show(quit=False)
main_menu(settings)
elif to_do == u"show_help":
usage.help()
else:
do_sync(settings, "")
def askYesNo(msg, default=None):
default = default and default.lower()
y = 'Y' if default == 'y' else 'y'
n = 'N' if default == 'n' else 'n'
prompt = msg + ' (%s/%s)? ' % (y, n)
value = None
while value is None:
value = input(prompt).lower()
if value == '' and default:
return default == 'y'
if value not in ('y', 'n', 'yes', 'no'):
value = None
return value in ('y', 'yes')
def get_file_abspath():
file_abspath = None
while file_abspath is None:
file_path = input('\nPath to your file: ')
if sys.platform.startswith('win'):
file_path = file_path.replace('/', os.sep)
else:
file_path = file_path.replace('\\', os.sep)
file_abspath = os.path.abspath(file_path)
if not os.path.isfile(file_abspath):
print('Invalid file path!')
file_abspath = None
return file_abspath
def get_encoding():
encoding = ENCODING
print('\nDefault encoding for input and output files:', encoding)
change_encoding_ans = None
while change_encoding_ans is None:
change_encoding_ans = input('Change encoding? [N/y] ')
if change_encoding_ans and change_encoding_ans[0].lower() == 'y':
new_encoding = None
while new_encoding is None:
new_encoding = input('New encoding: ')
if not new_encoding:
new_encoding = None
encoding = new_encoding
return encoding
def _call_validator(opttype, optdict, option, value):
if opttype not in VALIDATORS:
raise Exception('Unsupported type "%s"' % opttype)
try:
return VALIDATORS[opttype](optdict, option, value)
except TypeError:
try:
return VALIDATORS[opttype](value)
except optik_ext.OptionValueError:
raise
except:
raise optik_ext.OptionValueError('%s value (%r) should be of type %s' %
(option, value, opttype))
# user input functions ########################################################
# user input functions will ask the user for input on stdin then validate
# the result and return the validated value or raise optparse.OptionValueError
# XXX add to documentation
def format_option_value(optdict, value):
"""return the user input's value from a 'compiled' value"""
if isinstance(value, (list, tuple)):
value = ','.join(value)
elif isinstance(value, dict):
value = ','.join(['%s:%s' % (k, v) for k, v in value.items()])
elif hasattr(value, 'match'): # optdict.get('type') == 'regexp'
# compiled regexp
value = value.pattern
elif optdict.get('type') == 'yn':
value = value and 'yes' or 'no'
elif isinstance(value, string_types) and value.isspace():
value = "'%s'" % value
elif optdict.get('type') == 'time' and isinstance(value, (float, int, long)):
value = format_time(value)
elif optdict.get('type') == 'bytes' and hasattr(value, '__int__'):
value = format_bytes(value)
return value
def _call_validator(opttype, optdict, option, value):
if opttype not in VALIDATORS:
raise Exception('Unsupported type "%s"' % opttype)
try:
return VALIDATORS[opttype](optdict, option, value)
except TypeError:
try:
return VALIDATORS[opttype](value)
except optik_ext.OptionValueError:
raise
except:
raise optik_ext.OptionValueError('%s value (%r) should be of type %s' %
(option, value, opttype))
# user input functions ########################################################
# user input functions will ask the user for input on stdin then validate
# the result and return the validated value or raise optparse.OptionValueError
# XXX add to documentation
def format_option_value(optdict, value):
"""return the user input's value from a 'compiled' value"""
if isinstance(value, (list, tuple)):
value = ','.join(value)
elif isinstance(value, dict):
value = ','.join(['%s:%s' % (k, v) for k, v in value.items()])
elif hasattr(value, 'match'): # optdict.get('type') == 'regexp'
# compiled regexp
value = value.pattern
elif optdict.get('type') == 'yn':
value = value and 'yes' or 'no'
elif isinstance(value, string_types) and value.isspace():
value = "'%s'" % value
elif optdict.get('type') == 'time' and isinstance(value, (float, int, long)):
value = format_time(value)
elif optdict.get('type') == 'bytes' and hasattr(value, '__int__'):
value = format_bytes(value)
return value
def edit_file(file_path, ask=None):
# return True if user tries to edit the file
if ask:
try:
answer = input(ask)
except KeyboardInterrupt:
return False
if answer.lower() != "yes":
return False
editor = os.environ.get("EDITOR", Config.get("misc.editor"))
res = os.system("{} {}".format(editor, file_path))
if res != 0:
print("Error executing the default editor ({})".format(editor))
return res == 0
def __input_slack(self):
slack_conf = self.slack()
while True:
token = input("Please type for Slack api token. [required] %s : " % slack_conf["token"])
if not token:
if slack_conf["token"]:
token = slack_conf["token"]
break
else:
continue
else:
break
default_chanel = input("Please type for default channel. [not required] %s : " % slack_conf["channel"])
if not default_chanel and slack_conf["channel"]:
default_chanel = slack_conf["channel"]
bot_icon = input("Please type for image url. [not required] %s : " % slack_conf["bot_icon"])
if not bot_icon and slack_conf["bot_icon"]:
bot_icon = slack_conf["bot_icon"]
return { "token": token, "channel": default_chanel, "bot_icon": bot_icon }
def modifyChangelistUser(self, changelist, newUser):
# fixup the user field of a changelist after it has been submitted.
changes = p4CmdList("change -o %s" % changelist)
if len(changes) != 1:
die("Bad output from p4 change modifying %s to user %s" %
(changelist, newUser))
c = changes[0]
if c['User'] == newUser: return # nothing to do
c['User'] = newUser
input = marshal.dumps(c)
result = p4CmdList("change -f -i", stdin=input)
for r in result:
if 'code' in r:
if r['code'] == 'error':
die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
if 'data' in r:
print("Updated user field for changelist %s to %s" % (changelist, newUser))
return
die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
def cli(project, base_image, base_deps, add_deps, requirements):
project_dir = utils.get_project_dir()
scrapy_config = shub_utils.get_config()
if not scrapy_config.has_option('settings', project):
raise shub_exceptions.BadConfigException(
'Settings for the project is not found')
settings_module = scrapy_config.get('settings', project)
values = {
'base_image': base_image,
'system_deps': _format_system_deps(base_deps, add_deps),
'system_env': _format_system_env(settings_module),
'requirements': _format_requirements(project_dir, requirements),
}
values = {key: value if value else '' for key, value in values.items()}
source = Template(DOCKERFILE_TEMPLATE.strip())
results = source.substitute(values)
results = results.replace('\n\n', '\n')
click.echo("The following Dockerfile will be created:\n{}".format(results))
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
while True:
dockefile_path = os.path.join(project_dir, 'Dockerfile')
choice = input("Save to {}: (y/n)".format(dockefile_path)).lower()
if choice in valid:
if valid[choice]:
with open(dockefile_path, 'w') as dockerfile:
dockerfile.write(results)
click.echo('Saved.')
break
click.echo("Please respond with 'yes'('y') or 'no'(n)")
def init(args):
"""Initialize or edit an existing .osfcli.config file."""
# reading existing config file, convert to configparser object
config = config_from_file()
config_ = configparser.ConfigParser()
config_.add_section('osf')
if 'username' not in config.keys():
config_.set('osf', 'username', '')
else:
config_.set('osf', 'username', config['username'])
if 'project' not in config.keys():
config_.set('osf', 'project', '')
else:
config_.set('osf', 'project', config['project'])
# now we can start asking for new values
print('Provide a username for the config file [current username: {}]:'.format(
config_.get('osf', 'username')))
username = input()
if username:
config_.set('osf', 'username', username)
print('Provide a project for the config file [current project: {}]:'.format(
config_.get('osf', 'project')))
project = input()
if project:
config_.set('osf', 'project', project)
cfgfile = open(".osfcli.config", "w")
config_.write(cfgfile)
cfgfile.close()
def get_input(text=''):
i = input(text)
if isinstance(i, bytes):
return i.decode('utf-8', errors='replace')
return i