本文整理汇总了Python中six.moves.input函数的典型用法代码示例。如果您正苦于以下问题:Python input函数的具体用法?Python input怎么用?Python input使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了input函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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'])
示例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
示例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'
示例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()
示例7: main
def main():
pl = NBPlot()
for ii in range(10):
pl.plot()
time.sleep(0.5)
input('press Enter...')
pl.plot(finished=True)
示例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()
示例9: read_text
def read_text():
lines = []
line = input()
while line:
lines.append(line)
line = input()
return "\n\n".join(lines)
示例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
示例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
示例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)
示例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
示例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("")
示例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!")