本文整理汇总了Python中six.moves.input函数的典型用法代码示例。如果您正苦于以下问题:Python input函数的具体用法?Python input怎么用?Python input使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了input函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: connect
def connect(self, host, passwd=None, port=22):
print('Connecting...')
username, host = host.split('@')
if passwd is not None:
return self._connect_with_passwd(host, username, passwd, port)
else:
print('Looking for SSH keys...')
key_filename = self.find_ssh_keys()
if len(key_filename) > 0:
try:
self.client.connect(host,
username=username,
password=passwd,
port=port,
key_filename=key_filename)
return True
except paramiko.SSHException as e:
print('Failed to login with SSH Keys: {}'.format(repr(e)))
print('Trying password ...')
passwd = input('Enter password:')
return self._connect_with_passwd(host, username, passwd, port)
except Exception as e:
print('Error: {}'.format(e))
return False
else:
print('No SSH key found. Trying password ...')
passwd = input('Enter password:')
return self._connect_with_passwd(host, username, passwd, port)
开发者ID:BBOOXX,项目名称:stash,代码行数:31,代码来源:ssh.py
示例2: _CommandLine
def _CommandLine(args):
if 1 < len(args):
for arg in args[1:]:
if arg in ('-h', '--help'):
print('This program converts integers which may be signed ' +
'between any two number bases %d and over.\n' +
'Inputs as follows:\n' +
'inNum = the Input Number\n' +
'inBas = the Input Base\n' +
'outBas = the Output Base' % (MINIMUM_BASE))
break
elif arg in ('-t', '--test'):
import test
test.RunTests()
break
else:
print(BasCalc(*args[1:]))
else:
print('Base Converter')
exitVals = ('q', 'quit')
while True:
try:
print('Output Number: ' +
BasCalc(input('\nEnter an Input Number: ').strip(),
input('Enter an Input Base: ').strip(),
input('Enter an Output Base: ').strip()))
except (BaseConvError, ValueError) as e:
print('Error: ', e)
if input('\nEnter any of the following values to exit: %s\n' +
'or press return to continue: ' %
(str(exitVals))).strip().lower() in exitVals:
break
开发者ID:AaronRobson,项目名称:BaseConv,代码行数:32,代码来源:baseconv.py
示例3: run
def run(project, zone, instance_name):
credentials = GoogleCredentials.get_application_default()
compute = build('compute', 'v1', credentials=credentials)
print('Creating instance.')
operation = create_instance(compute, project, zone, instance_name)
wait_for_operation(compute, project, zone, operation['name'])
instances = list_instances(compute, project, zone)
print('Instances in project %s and zone %s:' % (project, zone))
for instance in instances:
print(' - ' + instance['name'])
print("""
Instance created.
It will take a minute or two for the instance to complete work.
Check this URL: http://storage.googleapis.com/%s/output.png
Once the image is uploaded press enter to delete the instance.
""" % project)
input()
print('Deleting instance.')
operation = delete_instance(compute, project, zone, instance_name)
wait_for_operation(compute, project, zone, operation['name'])
开发者ID:googlearchive,项目名称:compute-getting-started-python,代码行数:28,代码来源:main.py
示例4: apply_actions
def apply_actions(self, iw, actions):
action_meta = {'REDO': False}
if actions.count() > 0:
if self.dump_actions:
self.dump_action_dict(iw, actions)
if self.dry_run:
print("Dry-run specified, skipping execution of actions")
else:
if self.force:
print("Running actions non-interactive as you forced.")
self.execute_actions(iw, actions)
return action_meta
cont = input("Take recommended actions (y/N/a/R/T/DEBUG)? ")
if cont in ('a', 'A'):
sys.exit(0)
if cont in ('Y', 'y'):
self.execute_actions(iw, actions)
if cont == 'T':
self.template_wizard(iw)
action_meta['REDO'] = True
if cont in ('r', 'R'):
action_meta['REDO'] = True
if cont == 'DEBUG':
# put the user into a breakpoint to do live debug
action_meta['REDO'] = True
import epdb; epdb.st()
elif self.always_pause:
print("Skipping, but pause.")
cont = input("Continue (Y/n/a/R/T/DEBUG)? ")
if cont in ('a', 'A', 'n', 'N'):
sys.exit(0)
if cont == 'T':
self.template_wizard(iw)
action_meta['REDO'] = True
elif cont in ('r', 'R'):
action_meta['REDO'] = True
elif cont == 'DEBUG':
# put the user into a breakpoint to do live debug
import epdb; epdb.st()
action_meta['REDO'] = True
elif self.force_description_fixer:
# FIXME: self.FIXED_ISSUES not defined since 1cf9674cd38edbd17aff906d72296c99043e5c13
# either define self.FIXED_ISSUES, either remove this method
# FIXME force_description_fixer is not known by DefaultTriager (only
# by AnsibleTriage): if not removed, move it to AnsibleTriage
if iw.html_url not in self.FIXED_ISSUES:
if self.meta['template_missing_sections']:
changed = self.template_wizard(iw)
if changed:
action_meta['REDO'] = True
self.FIXED_ISSUES.append(iw.html_url)
else:
print("Skipping.")
# let the upper level code redo this issue
return action_meta
开发者ID:abadger,项目名称:ansibullbot,代码行数:60,代码来源:defaulttriager.py
示例5: test_stdin_from_generator_expression
def test_stdin_from_generator_expression():
generator = (x for x in ['one', 'two', 'three'])
with stdin_from(generator):
assert input() == 'one'
assert input() == 'two'
assert input() == 'three'
开发者ID:msabramo,项目名称:redirectory,代码行数:7,代码来源:test_redirectory.py
示例6: restTest
def restTest():
""""""
# 创建API对象并初始化
api = LbankRestApi()
api.init(API_KEY, SECRET_KEY)
api.start(1)
# 测试
#api.addReq('GET', '/currencyPairs.do', {}, api.onData)
#api.addReq('GET', '/accuracy.do', {}, api.onData)
#api.addReq('GET', '/ticker.do', {'symbol': 'eth_btc'}, api.onData)
#api.addReq('GET', '/depth.do', {'symbol': 'eth_btc', 'size': '5'}, api.onData)
#api.addReq('post', '/user_info.do', {}, api.onData)
req = {
'symbol': 'sc_btc',
'current_page': '1',
'page_length': '50'
}
api.addReq('POST', '/orders_info_no_deal.do', req, api.onData)
# 阻塞
input()
开发者ID:aaront2000,项目名称:vnpy,代码行数:25,代码来源:test.py
示例7: main
def main():
pl = NBPlot()
for ii in range(10):
pl.plot()
time.sleep(0.5)
input('press Enter...')
pl.plot(finished=True)
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:7,代码来源:multiprocess.py
示例8: private_key_copy
def private_key_copy(self):
log.debug(u'Copied private key')
self.key_handler.copy_decrypted_private_key()
msg = u'Private key decrypted. Press enter to continue'
self.display_msg(msg)
input()
self()
开发者ID:douglasmccormickjr,项目名称:PyiUpdater,代码行数:7,代码来源:keys.py
示例9: read_text
def read_text():
lines = []
line = input()
while line:
lines.append(line)
line = input()
return "\n\n".join(lines)
开发者ID:hornc,项目名称:openlibrary-1,代码行数:7,代码来源:utils.py
示例10: get_correct_answer
def get_correct_answer(question, default=None, required=False,
answer=None, is_answer_correct=None):
while 1:
if default is None:
msg = u' - No Default Available'
else:
msg = (u'\n[DEFAULT] -> {}\nPress Enter To '
'Use Default'.format(default))
prompt = question + msg + '\n--> '
if answer is None:
answer = input(prompt)
if answer == '' and required and default is not None:
print(u'You have to enter a value\n\n')
input(u'Press enter to continue')
print('\n\n')
answer = None
continue
if answer == u'' and default is not None:
answer = default
_ans = ask_yes_no(u'You entered {}, is this '
'correct?'.format(answer),
answer=is_answer_correct)
if _ans:
return answer
else:
answer = None
开发者ID:douglasmccormickjr,项目名称:PyiUpdater,代码行数:26,代码来源:menu_utils.py
示例11: pre_work
def pre_work(self):
# this method will be called before the gathering begins
localname = self.get_local_name()
if not self.commons['cmdlineopts'].batch and not self.commons['cmdlineopts'].quiet:
try:
self.report_name = input(_("Please enter your first initial and last name [%s]: ") % localname)
self.ticket_number = input(_("Please enter the case number that you are generating this report for: "))
self._print()
except:
self._print()
self.report_name = localname
if len(self.report_name) == 0:
self.report_name = localname
if self.commons['cmdlineopts'].customer_name:
self.report_name = self.commons['cmdlineopts'].customer_name
if self.commons['cmdlineopts'].ticket_number:
self.ticket_number = self.commons['cmdlineopts'].ticket_number
self.report_name = self.sanitize_report_name(self.report_name)
if self.ticket_number:
self.ticket_number = self.sanitize_ticket_number(self.ticket_number)
if (self.report_name == ""):
self.report_name = "default"
return
开发者ID:iweiss,项目名称:sos,代码行数:32,代码来源:__init__.py
示例12: setup_manager
def setup_manager(yes=False, port=23624, domain=None):
"Setup bench-manager.local site with the bench_manager app installed on it"
from six.moves import input
create_new_site = True
if 'bench-manager.local' in os.listdir('sites'):
ans = input('Site aleady exists. Overwrite existing new site? [Y/n]: ')
while ans.lower() not in ['y', 'n', '']:
ans = input('Please type "y" or "n". Site aleady exists. Overwrite existing new site? [Y/n]: ')
if ans=='n': create_new_site = False
if create_new_site: exec_cmd("bench new-site --force bench-manager.local")
if 'bench_manager' in os.listdir('apps'):
print('App aleady exists. Skipping downloading the app')
else:
exec_cmd("bench get-app bench_manager")
exec_cmd("bench --site bench-manager.local install-app bench_manager")
from bench.config.common_site_config import get_config
bench_path = '.'
conf = get_config(bench_path)
if conf.get('restart_supervisor_on_update') or conf.get('restart_systemd_on_update'):
# implicates a production setup or so I presume
if not domain:
print("Please specify the site name on which you want to host bench-manager using the 'domain' flag")
sys.exit(1)
from bench.utils import get_sites, get_bench_name
bench_name = get_bench_name(bench_path)
if domain not in get_sites(bench_path):
raise Exception("No such site")
from bench.config.nginx import make_bench_manager_nginx_conf
make_bench_manager_nginx_conf(bench_path, yes=yes, port=port, domain=domain)
开发者ID:hfaridgit,项目名称:bench,代码行数:35,代码来源:setup.py
示例13: allocate
def allocate(self, size):
from traceback import extract_stack
stack = tuple(frm[2] for frm in extract_stack())
description = self.describe(stack, size)
histogram = {}
for bsize, descr in six.itervalues(self.blocks):
histogram[bsize, descr] = histogram.get((bsize, descr), 0) + 1
from pytools import common_prefix
cpfx = common_prefix(descr for bsize, descr in histogram)
print(
"\n Allocation of size %d occurring "
"(mem: last_free:%d, free: %d, total:%d) (pool: held:%d, active:%d):"
"\n at: %s" % (
(size, self.last_free) + cuda.mem_get_info()
+ (self.held_blocks, self.active_blocks,
description)),
file=self.logfile)
hist_items = sorted(list(six.iteritems(histogram)))
for (bsize, descr), count in hist_items:
print(" %s (%d bytes): %dx" % (descr[len(cpfx):], bsize, count),
file=self.logfile)
if self.interactive:
input(" [Enter]")
result = DeviceMemoryPool.allocate(self, size)
self.blocks[result] = size, description
self.last_free, _ = cuda.mem_get_info()
return result
开发者ID:FreddieWitherden,项目名称:pycuda,代码行数:33,代码来源:tools.py
示例14: print_info
def print_info(machine_name, connections, width, height, ip_file_filename):
""" Print the current machine info in a human-readable form and wait for
the user to press enter.
Parameters
----------
machine_name : str
The machine the job is running on.
connections : {(x, y): hostname, ...}
The connections to the boards.
width, height : int
The width and height of the machine in chips.
ip_file_filename : str
"""
t = Terminal()
to_print = OrderedDict()
to_print["Hostname"] = t.bright(connections[(0, 0)])
to_print["Width"] = width
to_print["Height"] = height
if len(connections) > 1:
to_print["Num boards"] = len(connections)
to_print["All hostnames"] = ip_file_filename
to_print["Running on"] = machine_name
print(render_definitions(to_print))
try:
input(t.dim("<Press enter when done>"))
except (KeyboardInterrupt, EOFError):
print("")
开发者ID:project-rig,项目名称:spalloc,代码行数:34,代码来源:alloc.py
示例15: run
def run(argv=None):
"""Run the program
Usage: des.py [options] <bits>
It will ask you for further inputs
Options::
-h,--help Show this help
-v,--verbose Increase verbosity
--test Generate test strings
"""
import sys
import docopt
import textwrap
from binascii import unhexlify, hexlify
from multiprocessing import Pool
argv = sys.argv[1:]
args = docopt.docopt(textwrap.dedent(run.__doc__), argv)
nbits = int(args['<bits>'])
# set up logging
level = logging.WARN
if args['--verbose']:
level = logging.INFO
logging.basicConfig(level=level)
if args['--test']:
from random import randint
key1 = nth_key(randint(0, 2**nbits))
key2 = nth_key(randint(0, 2**nbits))
plain_text = bytes((randint(0, 255) for i in range(8)))
cipher_text = encrypt(key2, encrypt(key1, plain_text))
print("key: ({}, {})".format(hexlify(key1).decode('utf-8'),
hexlify(key2).decode('utf-8')))
print("plain text: {}".format(hexlify(plain_text).decode('utf-8')))
print("cipher text: {}".format(hexlify(cipher_text).decode('utf-8')))
return
input_more = True
pairs = []
while input_more:
plain_text = unhexlify(
input("Please input the plain text, hex encoded: "
).strip().encode('utf-8'))
cipher_text = unhexlify(
input("Please input the cipher text, hex encoded: "
).strip().encode('utf-8'))
pairs.append((plain_text, cipher_text))
if 'y' not in input("Do you want to supply more texts? [y/N]: "):
input_more = False
with Pool() as p:
keys = meet_in_the_middle(nbits, pairs, pool=p)
if keys:
print("Found keys: ({}, {})".format(*keys))
else:
print("Did not find keys!")
开发者ID:gh0std4ncer,项目名称:des-meet-in-the-middle,代码行数:60,代码来源:des.py
示例16: save_config
def save_config(config):
"""設定を保存.
:param config:
:return:
"""
config_path = Path(config.config_path)
if not config_path.exists():
allow = True
else:
allow = _confirm("overwrite %s \nOK?" % str(config_path))
if allow:
print("enter your region[us-east-1]:")
region = moves.input() or "us-east-1"
with config_path.open("w") as fp:
print("save to %s" % str(config_path))
fp.write(DEFAULT_CONFIG.format(region=region))
key_file = Path(config.config.get('key_file'))
if key_file.exists():
allow = _confirm("overwrite %s \nOK?" % str(key_file))
else:
allow = True
if allow:
print("enter your aws_access_key_id:")
key_id = moves.input()
print("enter your aws_secret_access_key:")
secret_key = moves.input()
if key_id and secret_key:
print("save to %s" % key_file)
with key_file.open("w") as fp:
fp.write(u"%s:%s" % (key_id, secret_key))
开发者ID:takada-at,项目名称:sg,代码行数:32,代码来源:service.py
示例17: setup_package_options
def setup_package_options(self):
self.package_options = self.DEFAULT_PACKAGE_OPTIONS
print('Choose between the following strategies : ')
strategies = list(strategies_class_lookup.keys())
for istrategy, strategy in enumerate(strategies):
print(' <{}> : {}'.format(str(istrategy + 1), strategy))
test = input(' ... ')
self.package_options['default_strategy'] = {'strategy': strategies[int(test) - 1], 'strategy_options': {}}
strategy_class = strategies_class_lookup[strategies[int(test) - 1]]
if len(strategy_class.STRATEGY_OPTIONS) > 0:
for option, option_dict in strategy_class.STRATEGY_OPTIONS.items():
while True:
print(' => Enter value for option "{}" '
'(<ENTER> for default = {})\n'.format(option,
str(option_dict['default'])))
print(' Valid options are :\n')
print(' {}'.format(option_dict['type'].allowed_values))
test = input(' Your choice : ')
if test == '':
self.package_options['default_strategy']['strategy_options'][option] = option_dict['type'](strategy_class.STRATEGY_OPTIONS[option]['default'])
break
try:
self.package_options['default_strategy']['strategy_options'][option] = option_dict['type'](test)
break
except ValueError:
print('Wrong input for option {}'.format(option))
开发者ID:albalu,项目名称:pymatgen,代码行数:26,代码来源:chemenv_config.py
示例18: aws_sign_in
def aws_sign_in(aws_profile, duration_minutes=DEFAULT_SIGN_IN_DURATION_MINUTES,
force_new=False):
"""
Create a temp session through MFA for a given aws profile
:param aws_profile: The name of an existing aws profile to create a temp session for
:param duration_minutes: How long to set the session expiration if a new one is created
:param force_new: If set to True, creates new credentials even if valid ones are found
:return: The name of temp session profile.
(Always the passed in profile followed by ':session')
"""
aws_session_profile = '{}:session'.format(aws_profile)
if not force_new \
and _has_valid_session_credentials(aws_session_profile):
return aws_session_profile
default_username = get_default_username()
if default_username.is_guess:
username = input("Enter username associated with credentials [{}]: ".format(
default_username)) or default_username
print_help_message_about_the_commcare_cloud_default_username_env_var(username)
else:
username = default_username
mfa_token = input("Enter your MFA token: ")
generate_session_profile(aws_profile, username, mfa_token, duration_minutes)
puts(colored.green(u"✓ Sign in accepted"))
puts(colored.cyan(
"You will be able to use AWS from the command line for the next {} minutes."
.format(duration_minutes)))
puts(colored.cyan(
"To use this session outside of commcare-cloud, "
"prefix your command with AWS_PROFILE={}:session".format(aws_profile)))
return aws_session_profile
开发者ID:dimagi,项目名称:commcarehq-ansible,代码行数:34,代码来源:aws.py
示例19: ask_option
def ask_option(message, options, acceptable_responses=None):
options_display = '/'.join(options)
acceptable_responses = acceptable_responses or options
r = input('{} [{}]'.format(message, options_display))
while r not in acceptable_responses:
r = input('Please enter one of {} :'.format(', '.join(options)))
return r
开发者ID:dimagi,项目名称:commcarehq-ansible,代码行数:7,代码来源:cli_utils.py
示例20: main
def main():
x = mtb.xcard()
print('---')
pwd = input('Enter your new password (digits only, 8 chars: ')
if len(pwd) != 8 or not pwd.isdigit():
raise Exception('Bad password, try again')
pan = input('Enter your x-card number: ')
cvc = input('Enter your cvc2 code: ')
r = x.register(pan, cvc)
# otp request
otp = input('Enter your SMS code: ')
o = x.confirmotp(otp.strip())
# password
x.setpassword(pwd)
print('Registered')
print('---')
print('password:', pwd)
print('userId:', r['userId'])
print('-')
print('CARDREF (not needed?):', r['CARDREF'])
print('trsaPub (not nneded?):', o['trsaPub'])
开发者ID:004helix,项目名称:bybankpy,代码行数:26,代码来源:xcard-register.py
注:本文中的six.moves.input函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论