def prompt(text=None, choices=None, default=None): """Create a prompt of text is given,then offer choices with a default. e.g. prompt('how are you?',['good','bad'],['good']""" if text is None: text = "" use_choices = None if choices is not None: if type(choices) is list: use_choices = dict(zip(choices, choices)) elif type(choices) is dict: use_choices = choices while True: if use_choices is None: ans = six.input("{text}: ".format(text=text)) if not ans: return default else: return ans else: # choices ans = six.input("{text} [{choices}]: ".format( text=text, choices=",".join(use_choices.keys()))) for k in use_choices.keys(): if (type(use_choices[k]) == str and ans == use_choices[k]) or\ (type(use_choices[k]) == list and ans in use_choices[k]): return k #no choice found if default is not None: return default message("Please enter one of the choices.") continue
def web_based_app(): """Emulation of web-based app. Your keys should be created with project type "Web". Returns: ``odesk.Client`` instance ready to work. """ print("Emulating web-based app") public_key = input('Please enter public key: > ') secret_key = input('Please enter secret key: > ') #Instantiating a client without an auth token client = odesk.Client(public_key, secret_key) print("Please to this URL (authorize the app if necessary):") print(client.auth.get_authorize_url()) print("After that you should be redirected back to your app URL with " "additional ?oauth_verifier= parameter") verifier = input('Enter oauth_verifier: ') oauth_access_token, oauth_access_token_secret = \ client.auth.get_access_token(verifier) # Instantiating a new client, now with a token. # Not strictly necessary here (could just set `client.oauth_access_token` # and `client.oauth_access_token_secret`), but typical for web apps, # which wouldn't probably keep client instances between requests client = odesk.Client(public_key, secret_key, oauth_access_token=oauth_access_token, oauth_access_token_secret=oauth_access_token_secret) return client
def migrate(): q_status = model.Session.query(model.TaskStatus) \ .filter_by(task_type='qa') \ .filter_by(key='status') print('* %s with "status" will be deleted e.g. %s' % (q_status.count(), q_status.first())) q_failures = model.Session.query(model.TaskStatus) \ .filter_by(task_type='qa') \ .filter_by(key='openness_score_failure_count') print('* %s with openness_score_failure_count to be deleted e.g.\n%s' % (q_failures.count(), q_failures.first())) q_score = model.Session.query(model.TaskStatus) \ .filter_by(task_type='qa') \ .filter_by(key='openness_score') print('* %s with openness_score to migrate e.g.\n%s' % (q_score.count(), q_score.first())) q_reason = model.Session.query(model.TaskStatus) \ .filter_by(task_type='qa') \ .filter_by(key='openness_score_reason') print('* %s with openness_score_reason to migrate e.g.\n%s' % (q_reason.count(), q_reason.first())) six.input('Press Enter to continue') q_status.delete() model.Session.commit() print('..."status" deleted') q_failures.delete() model.Session.commit() print('..."openness_score_failure_count" deleted') for task_status in q_score: reason_task_status = q_reason \ .filter_by(entity_id=task_status.entity_id) \ .first() if reason_task_status: reason = reason_task_status.value reason_task_status.delete() else: reason = None task_status.key = 'status' task_status.error = json.dumps({ 'reason': reason, 'format': None, 'is_broken': None, }) model.Session.commit() print('..."openness_score" and "openness_score_reason" migrated') count = q_reason.count() q_reason.delete() model.Session.commit() print('... %i remaining "openness_score_reason" deleted' % count) model.Session.flush() model.Session.remove() print('Migration succeeded')
def main(): import six print("applying rules") run_cmds(start_cmds) six.input("Press Enter to continue...") run_cmds(end_cmds)
def user_input(self): print('number\tfunction\tfile\tcode') counter = 0 stack = traceback.extract_stack() for e in stack: print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3])) counter += 1 print(single_line_delim) print("You can enter a number of stack frame chosen from above") print("Calls in/below that stack frame will be not be stepped anymore") print(single_line_delim) while True: choice = six.input("Enter your choice, if any, and press ENTER to " "continue running the testcase...") if choice == "": choice = None try: if choice is not None: num = int(choice) except Exception: print("Invalid input") continue if choice is not None and (num < 0 or num >= len(stack)): print("Invalid choice") continue break if choice is not None: self.skip_stack = stack self.skip_num = num
def main(): # server_name = rospy.resolve_name('~data_collection_server') # root_dir = osp.expanduser(rospy.get_param('~root_dir')) server_name = '/data_collection_server' root_dir = osp.expanduser('~/.ros/instance_occlsegm') caller = rospy.ServiceProxy('%s/save_request' % server_name, Trigger) client = Client(server_name) action = 'n' # to initialize while not rospy.is_shutdown(): while action not in ['n', 's', 'q']: action = six.input( 'Please select actions: [n] New save_dir, [s] Save, [q] Quit: ' ) action = action.strip().lower() if action == 'n': now = rospy.Time.now() save_dir = osp.join(root_dir, str(now.to_nsec())) client.update_configuration({'save_dir': save_dir}) print('-' * 79) print('Updated save_dir to: {}'.format(save_dir)) elif action == 's': res = caller.call() print('Sent request to data_collection_server') print(res) else: assert action == 'q' return action = None
def input_yesno(prompt="[Y/n] "): while True: resp = six.input("[Y/n] ").strip().lower() if (resp == "") or resp.startswith("y"): return True elif resp.startswith("n"): return False
def do_destroy(prefix, yes, all_prefixes, parent_workdir, prefix_name, **kwargs): if all_prefixes: warn_message = 'all the prefixes under ' + parent_workdir.path path = parent_workdir.path else: warn_message = prefix.paths.prefix_path() path = warn_message if not yes: response = six.input('Do you really want to destroy %s? [Yn] ' % warn_message) if response and response[0] not in 'Yy': LOGGER.info('Aborting on user input') return if os.path.islink(path): os.unlink(path) return if all_prefixes: parent_workdir.destroy() elif parent_workdir: parent_workdir.destroy([prefix_name]) else: prefix.destroy()
def printmenu(): print("Update database main menu:") print("1. Enter search tags (refine search).") print("2. Print matching available files.") print("3. Print all available files.") print("4. Update all local files.") print("0. Exit.") return six.input("Select option:")
def get_input(prompt): try: r = six.input(prompt) z = r if z.rstrip().endswith(':'): while True: try: z = six.input('... ') except EOFError: quit = True break if z != '': r += '\n ' + z else: break return r except EOFError: return None
def pick_checklist(registry): checklist_names = sorted(registry.keys()) while True: for ii, checklist_name in enumerate(checklist_names): print("[%d] %s" % (ii, checklist_name)) index = six.input(">>> ") try: return checklist_names[int(index)] except (IndexError, TypeError, ValueError): print("") print("Please select a number from the list:")
def _confirm_merge(self, primary_user, other_users): message = "Merge {} into {}? [Yn] ".format( ', '.join(o.username for o in other_users), primary_user.username, ) while True: response = six.input(message).strip().lower() if response in ('y', ''): return True elif response == 'n': return False
def input_with_prefill(prompt, text): def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = six.input(prompt) # nosec (bandit; python2) readline.set_pre_input_hook() return result
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" # If authenticator is not plugged in, prompt try: device = u2f.GetLocalU2FInterface(origin=self.origin) except errors.NoDeviceFoundError: print_callback( 'Please insert your security key and press enter...') six.input() device = u2f.GetLocalU2FInterface(origin=self.origin) print_callback('Please touch your security key.\n') for challenge_item in challenge_data: raw_challenge = challenge_item['challenge'] key = challenge_item['key'] try: result = device.Authenticate(app_id, raw_challenge, [key]) except errors.U2FError as e: if e.code == errors.U2FError.DEVICE_INELIGIBLE: continue else: raise client_data = self._base64encode( result.client_data.GetJson().encode()) signature_data = self._base64encode(result.signature_data) key_handle = self._base64encode(result.key_handle) return { 'clientData': client_data, 'signatureData': signature_data, 'applicationId': app_id, 'keyHandle': key_handle, } raise errors.U2FError(errors.U2FError.DEVICE_INELIGIBLE)
def prompt(self, message): """ Helper function that is being used to ask the user for confirmation :param message: Message to be printed (To ask the user to confirm ...) :return: True or False """ if self.conf['yes']: return self.conf['yes'] while True: ans = six.input(message) if ans.lower() == 'y': return True elif ans.lower() == 'n': return False
def process_domain(self, csvfile, args): domain = csvfile.split("/")[-1].split(".csv")[0] domain_obj = self.BaseDomain.find(domain=domain) if not domain_obj: print("Error: Domain not found: %s" % domain) return csvdata = open(csvfile).read().decode("utf-16").encode("utf-8") csvreader = csv.reader(BytesIO(csvdata), delimiter=",", quotechar='"') headers = csvreader.next() searchable_headers = ["Author", "Creator"] indexes = [headers.index(s) for s in searchable_headers if s in headers] data = [] for row in csvreader: for i in indexes: data.append(row[i]) data = list(set(data)) # Dedup for d in data: if d.strip(): res = six.input("Is %s a valid name? [y/N] " % d) if res and res[0].lower() == "y": if " " in d: if ", " in d: first_name = d.split(", ")[1] last_name = d.split(", ")[0] else: first_name = d.split(" ")[0] last_name = " ".join(d.split(" ")[1:]) created, user = self.User.find_or_create( first_name=first_name, last_name=last_name ) if created: print("New user created") user.domain = domain_obj # else: # created, user = self.User.find_or_create(username=d) # if created: # print("New username created") # user.domain = domain_obj user.update() self.User.commit()
def run_raptor(self, **kwargs): build_obj = self is_android = Conditions.is_android(build_obj) or \ kwargs['app'] in FIREFOX_ANDROID_BROWSERS if is_android: from mozrunner.devices.android_device import ( verify_android_device, InstallIntent) from mozdevice import ADBAndroid, ADBHost install = InstallIntent.NO if kwargs.pop( 'noinstall', False) else InstallIntent.PROMPT if not verify_android_device( build_obj, install=install, app=kwargs['binary'], xre=True): # Equivalent to 'run_local' = True. return 1 debug_command = '--debug-command' if debug_command in sys.argv: sys.argv.remove(debug_command) raptor = self._spawn(RaptorRunner) try: if is_android and kwargs['power_test']: device = ADBAndroid(verbose=True) adbhost = ADBHost(verbose=True) device_serial = "{}:5555".format(device.get_ip_address()) device.command_output(["tcpip", "5555"]) six.input( "Please disconnect your device from USB then press Enter/return..." ) adbhost.command_output(["connect", device_serial]) while len(adbhost.devices()) > 1: six.input( "You must disconnect your device from USB before continuing." ) # must reset the environment DEVICE_SERIAL which was set during # verify_android_device to match our new tcpip value. os.environ["DEVICE_SERIAL"] = device_serial return raptor.run_test(sys.argv[2:], kwargs) except Exception as e: print(repr(e)) return 1 finally: try: if is_android and kwargs['power_test']: six.input( "Connect device via USB and press Enter/return...") device = ADBAndroid(device=device_serial, verbose=True) device.command_output(["usb"]) adbhost.command_output(["disconnect", device_serial]) except Exception: adbhost.command_output(["kill-server"])
def confirm(self, prompt): """Prompt an user confirmation. Raise `UserAbort` if the user replies "no". The method is no-op if the ``--yes`` option is specified. """ if self.opts.yes: return True while 1: ans = six.input(_("%s [y/N] ") % prompt) if _('no').startswith(ans.lower()): raise UserAbort(_("operation interrupted on user request")) elif _('yes').startswith(ans.lower()): return True else: prompt = _("Please answer yes or no")
def searchmenu(): def printmenu(): print("\tSearch tags:", search) print("\t1. Add tag.") print("\t2. Clear tags.") print("\t0. Return to main menu.") return six.input("\tSelect option:") search = searchstr while True: response = printmenu().strip() if response == "1": search += " " + six.input("\tType new tag/tags:") elif response == "2": search = "" elif response == "0": break else: print("\tUnknown option!") return search
def filemenu(searchstr=""): files = [None] for i, (dom, file) in enumerate(sf.search(searchstr.split())): print("\t%i." % (i + 1), info[dom][file]["title"]) files.append((dom, file)) print("\t0. Return to main menu.") print("\tAction: d-download (e.g. 'd 1' downloads first file)") while True: response = six.input("\tAction:").strip() if response == "0": break try: action, num = response.split(None, 1) num = int(num) except Exception as ex: print("Unknown option!") continue try: if action.lower() == "d": download(*(files[num])) print("\tSuccsessfully downloaded", files[num][-1]) except Exception as ex: print("Error occured!", ex)
def show_menu(CommandClass, CompleterClass, name): command = CommandClass(name) completer = CompleterClass(command) readline.set_completer(completer.complete) readline.set_completer_delims(" ") readline.parse_and_bind("tab: complete") res = False while res is not True: valid_commands = command.cmd.keys() ret_cmd = six.input("%s> " % name).strip() cmd, options = (ret_cmd.split(" ")[0], " ".join(ret_cmd.split(" ")[1:])) if cmd == "debug": pdb.set_trace() elif cmd.lower() in valid_commands: res = command.run_cmd(cmd, options) else: print("Invalid command.") readline.set_completer(completer.complete)
def get_credentials(self): # FIXME(alikins) replace with a display callback print(u'\n\n' + "We need your " + 'Github login' + " to identify you.") print("This information will " + "not be sent to Galaxy" + ", only to " + "api.github.com.") print("The password will not be displayed." + u'\n\n') print("Use " + "--github-token" + " if you do not want to enter your password." + u'\n\n') try: self.github_username = six.input("Github Username: "******"Password for %s: " % self.github_username) except: pass if not self.github_username or not self.github_password: raise exceptions.GalaxyClientError( "Invalid Github credentials. Username and password are required." )
def make_client(zhmc, userid=None, password=None): """ Create a `Session` object for the specified HMC and log that on. Create a `Client` object using that `Session` object, and return it. If no userid and password are specified, and if no previous call to this method was made, userid and password are interactively inquired. Userid and password are saved in module-global variables for future calls to this method. """ global USERID, PASSWORD # pylint: disable=global-statement USERID = userid or USERID or \ six.input('Enter userid for HMC {}: '.format(zhmc)) PASSWORD = password or PASSWORD or \ getpass.getpass('Enter password for {}: '.format(USERID)) session = zhmcclient.Session(zhmc, USERID, PASSWORD) session.logon() client = zhmcclient.Client(session) print('Established logged-on session with HMC {} using userid {}'. format(zhmc, USERID)) return client
def reclassify_domain(self, bd): if bd.meta.get("whois", False): display_new("Whois data found for {}".format(bd.domain)) print(bd.meta["whois"]) res = six.input( "Should this domain be scoped (A)ctive, (P)assive, or (N)ot? [a/p/N] " ) if res.lower() == "a": bd.in_scope = True bd.passive_scope = True elif res.lower() == "p": bd.in_scope = False bd.passive_scope = True else: bd.in_scope = False bd.passive_scope = False bd.save() else: display_error( "Unfortunately, there is no whois information for {}. Please populate it using the Whois module".format( bd.domain ) )
GPIO.setwarnings(False) if cmd == "pwm": #print "Initialised pin "+str(pin)+" to PWM" try: freq = int(sys.argv[3]) except: freq = 100 GPIO.setup(pin, GPIO.OUT) p = GPIO.PWM(pin, freq) p.start(0) while True: try: data = six.input() if 'close' in data: sys.exit(0) p.ChangeDutyCycle(float(data)) except (EOFError, SystemExit ): # hopefully always caused by us sigint'ing the program GPIO.cleanup(pin) sys.exit(0) except Exception as ex: six.print_("bad data: " + data) elif cmd == "buzz": #print "Initialised pin "+str(pin)+" to Buzz" GPIO.setup(pin, GPIO.OUT) p = GPIO.PWM(pin, 100) p.stop()
def printmenu(): print("\tSearch tags:", search) print("\t1. Add tag.") print("\t2. Clear tags.") print("\t0. Return to main menu.") return six.input("\tSelect option:")
def warn_user(): while True: warning = "WARNING, this library has not been tested and might not work!\r\nType: 'ok' to continue: " result = six.input(warning) if result.lower() == "ok": break
def handle(self, **options): extension = options.get('ext') force = options.get('force') overwrite = options.get('overwrite') app_first = options.get('app_first') delete = options.get('delete') if not extension.startswith("."): extension = ".%s" % extension try: site = Site.objects.get_current() except Exception: raise CommandError("Please make sure to have the sites contrib " "app installed and setup with a site object") if app_first: tpl_dirs = app_template_dirs + DIRS else: tpl_dirs = DIRS + app_template_dirs templatedirs = [d for d in tpl_dirs if os.path.isdir(d)] for templatedir in templatedirs: for dirpath, subdirs, filenames in os.walk(templatedir): for f in [ f for f in filenames if f.endswith(extension) and not f.startswith(".") ]: path = os.path.join(dirpath, f) name = path.split(templatedir)[1] if name.startswith('/'): name = name[1:] try: t = Template.on_site.get(name__exact=name) except Template.DoesNotExist: if not force: confirm = input( "\nA '%s' template doesn't exist in the " "database.\nCreate it with '%s'?" " (y/[n]): " "" % (name, path)) if force or confirm.lower().startswith('y'): with io.open(path, encoding='utf-8') as f: t = Template(name=name, content=f.read()) t.save() t.sites.add(site) else: while 1: if overwrite == ALWAYS_ASK: confirm = input( "\n%(template)s exists in the database.\n" "(1) Overwrite %(template)s with '%(path)s'\n" "(2) Overwrite '%(path)s' with %(template)s\n" "Type 1 or 2 or press <Enter> to skip: " % { 'template': t.__repr__(), 'path': path }) else: confirm = overwrite if confirm in ('', FILES_TO_DATABASE, DATABASE_TO_FILES): if confirm == FILES_TO_DATABASE: with io.open(path, encoding='utf-8') as f: t.content = f.read() t.save() t.sites.add(site) if delete: try: os.remove(path) except OSError: raise CommandError( u"Couldn't delete %s" % path) elif confirm == DATABASE_TO_FILES: with io.open(path, 'w', encoding='utf-8') as f: f.write(t.content) if delete: t.delete() break
print('Creating FlickrAPI object') flickr = FlickrAPI(keys.apikey, keys.apisecret) # ------------------------------------------------------------------------------ print('Step 1: authenticate') if not flickr.token_valid(perms='read'): # Get a request token flickr.get_request_token(oauth_callback='oob') # Open a browser at the authentication URL. Do this however # you want, as long as the user visits that URL. authorize_url = flickr.auth_url(perms='read') webbrowser.open_new_tab(authorize_url) # Get the verifier code from the user. Do this however you # want, as long as the user gives the application the code. verifier = six.text_type(six.input('Verifier code: ')) # Trade the request token for an access token flickr.get_access_token(verifier) # ------------------------------------------------------------------------------ print('Step 2: use Flickr') resp = flickr.photos.getInfo(photo_id='7658567128') ET.dump(resp)
def _dispatch(self, client_method): """ Dispatches a single command, and also handles session setup and some types of errors. The set_args() method MUST be called first. :param client_method: Method name to invoke on the Client instance :type client_method: str """ assert (type(self._args) is argparse.Namespace) # Find a configuration file. The path can be specified as an # argument or an environment variable. Failing those we fall # back to a default location. filename = getattr(self._args, 'config', os.getenv('COMMCTL_CONFIG', default_config_file())) # Set up the Client instance, maybe interactively. conf = {} try: with open(filename) as cf: conf = json.load(cf) except IOError as ex: # pragma no cover # If file not found, prompt. if ex.errno != errno.ENOENT: self.argument_parser.error( 'Configuration file {0} could not be opened ' 'for reading'.format(self._args.config)) except ValueError: # pragma no cover self.argument_parser.error( ('Unable to parse configuration file. HINT: Make sure to ' 'use only double quotes and the last item should not end ' 'with a comma.')) # Prompt for any missing configuration. requires_user_pass = True if 'endpoint' not in conf.keys(): conf['endpoint'] = six.input('Endpoint: ') if 'kubeconfig' in conf.keys(): # If we have a kubeconfig entry move along. It will be handled # once the Client is created. requires_user_pass = False if requires_user_pass: if 'username' not in conf.keys(): conf['username'] = six.input('Username: '******'password' not in conf.keys(): import getpass conf['password'] = getpass.getpass() if type(conf['endpoint']) is not list: conf['endpoint'] = [conf['endpoint']] client = Client(conf) # Dispatch the appropriate method for the command. try: bound_method = getattr(client, client_method) call_result = bound_method(**self._args.__dict__) # XXX Don't dump scalars. yaml.dump() appends an # ugly-looking end-of-document marker (\n...). # # Also avoid tick marks on a list of scalars # so it can serve an input to another command. list_of_scalars = (type(call_result) is list and all(not hasattr(x, '__iter__') for x in call_result)) if list_of_scalars: output_data = '\n'.join([str(x) for x in call_result]) elif hasattr(call_result, '__iter__'): output_data = yaml.dump(call_result, default_flow_style=False, Dumper=yaml.SafeDumper, explicit_end=False) else: output_data = str(call_result) print(output_data.strip()) except NoMoreServersError as nmse: print("No servers could be reached. Tried the following:") for server in nmse.args: print("- {0}".format(server)) print("Exiting...") raise SystemExit(1) except requests.exceptions.RequestException as re: self.argument_parser.error(re) except ClientError as ce: self.argument_parser.error(ce)
#---------------------------------------------------------------------- def onChart(symbol, seconds): """K线更新""" print('-' * 30) print('onChart') if seconds == 0: serial = api.get_tick_serial(symbol) else: serial = api.get_kline_serial(symbol, seconds) print(serial) if __name__ == "__main__": symbol = 'CFFEX.IF1710' api = TqApi() api.connect() # 订阅Tick推送 #api.subscribe_quote([symbol], onQuote) # 订阅Tick图表 #api.subscribe_chart(symbol, 0, 100, onChart) # 订阅K线图表 api.subscribe_chart(symbol, 60, 1000, onChart) input()