def __config(self): global portSelection configList = [{ 'selector': '1', 'prompt': 'Set Baud Rate' }, { 'selector': '2', 'prompt': 'Set Login Details' }, { 'selector': '3', 'prompt': 'Set AT Library' }, { 'selector': '4', 'prompt': 'Change Device' }, { 'selector': '5', 'prompt': 'About' }, { 'selector': '0', 'prompt': 'Back' }] config = int(prompt.options("Config:", configList)) if config == 1: baudRate = prompt.query("Baud rate:", validators=[validators.IntegerValidator()]) self.__modifyConfigFiles('BaudRate', baudRate) elif config == 2: print 'Under Construction...' os.environ["SIGFOX_USR"] = prompt.query("Username:"******"SIGFOX_PWD"] = getpass.getpass('Password:'******'Error' raw_input("Press Enter to continue...") self.__config()
def geturl(url, dst): if os.path.isfile(dst): halt_exec = prompt.options("A file already exists with that name. Continue?", options=[ {'selector': 'Y', 'prompt': 'yes', 'return': False}, {'selector': 'N', 'prompt': 'no', 'return': True} ]) if halt_exec: raise SystemExit('Move the file and try again') try: req = requests.get(url, stream=True) req.raise_for_status() except requests.exceptions.HTTPError: raise SystemExit( "There was an error retrieving the data. Check your internet connection and try again." ) with open(dst, "wb") as f: total_length = req.headers.get('content-length') if total_length is None: # no content length header f.write(req.content) else: total_length = int(total_length) for chunk in progress.bar(req.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): if chunk: f.write(chunk) f.flush()
def main(): # Standard non-empty input #name = prompt.query("What's your name?") # Set validators to an empty list for an optional input #language = prompt.query("Your favorite tool (optional)?", validators=[]) # Shows a list of options to select from inst_options = [{'selector':'1','prompt':'iSCSI','return':connector.ISCSI}, {'selector':'2','prompt':'FibreChannel','return':connector.FIBRE_CHANNEL}, ] inst = prompt.options("Select Volume transport protocol", inst_options) if inst == connector.ISCSI: connection_info = iscsi_func() elif inst == connector.FIBRE_CHANNEL: connection_info = fc_func() # Use a default value and a validator #path = prompt.query('Installation Path', default='/usr/local/bin/', validators=[validators.PathValidator()]) #puts(colored.blue('Hi {0}. Install {1} {2} to {3}'.format(name, inst, language or 'nothing', path))) puts(colored.blue('Attempting to attach to {0} volume'.format(inst))) puts(colored.blue('Using {0}'.format(connection_info))) do_attach(connection_info)
def main(): """Run puckfetcher on the command line.""" parser = _setup_program_arguments() args = parser.parse_args() (cache_dir, config_dir, data_dir, log_dir) = _setup_directories(args) logger = _setup_logging(log_dir) config = Config.Config(config_dir=config_dir, cache_dir=cache_dir, data_dir=data_dir) index = 1 command_options = [{"selector": str(index), "prompt": "Exit.", "return": _Command.exit.name}] index += 1 config_commands = config.get_commands() for key in config_commands.keys(): value = config.commands[key] command_options.append({"selector": str(index), "prompt": value, "return": key.name}) index += 1 # See if we got a command-line command. config_dir = vars(args)["config"] command = vars(args)["command"] if command: if command == _Command.exit.name: _handle_exit(parser) elif command == _Command.prompt.name: pass else: # TODO do something cleaner than passing all this to handle_command. _handle_command(command, config, command_options) _handle_exit(parser) logger.info("%s %s started!", __package__, CONSTANTS.VERSION) # TODO CLI should probably print and not log. while True: try: command = prompt.options("Choose a command", command_options) if command == _Command.exit.name: _handle_exit(parser) _handle_command(command, config, command_options) # TODO look into replacing with # https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python except KeyboardInterrupt: logger.critical("Received KeyboardInterrupt, exiting.") break except EOFError: logger.critical("Received EOFError, exiting.") break parser.exit()
def select_backup(self, dumps_root): """ Returns the latest 10 dumps available in the dumps_root directory. Dumps are sorted by date, latests first """ backups = [] if os.path.exists(dumps_root): backups = os.listdir(dumps_root) backups = filter(lambda f: f.endswith(".dump"), backups) backups = list(backups) backups.sort(key=get_dtm_from_backup_name, reverse=True) backups = backups[:10] # don't show more than 10 backups if not backups: raise RuntimeError("Could not find a database backup}") # Shows a list of options to select from backup_options = [{ "selector": str(sel + 1), "prompt": get_dtm_from_backup_name(backup), "return": backup, } for sel, backup in enumerate(backups)] selected_backup = prompt.options( "Type the number in brackets to select the backup to be restored", backup_options, ) return os.path.join(dumps_root, selected_backup)
def _choose_sub(config): sub_names = config.get_subs() subscription_options = [] for i, sub_name in enumerate(sub_names): subscription_options.append({"selector": str(i+1), "prompt": sub_name, "return": i}) return prompt.options("Choose a subscription:", subscription_options)
def new_search(user): """ Does a new research. :param user: user previously registered. Used to register a favorite. """ # asks the user to choose a category among the categories registered category = category_selection() category = Category(name=category) # asks the user to choose among products registered in this category product = product_selection(category=category) product = Product(link=product[1], name=product[0], nutriscore=product[2]) # searches for a substitute substitute = Product.objects.get_better_products_by_category(category) substitute = substitute[0] substitute = Product( link=substitute["link"], name=substitute["name"], nutriscore=substitute["nutriscore"]) substitute.stores = Store.objects.get_stores_by_product(substitute) substitute_proposal(substitute, product) save_product = [{'selector': 'o', 'prompt': 'oui', 'return': 1}, {'selector': 'n', 'prompt': 'non', 'return': 0}] favorite = prompt.options( "voulez-vous enregistrer ce produit dans vos favoris ? ", save_product) if favorite: User.objects.insert_favorite(user, product, substitute)
def main(): """ Main function running the code """ user = hello() # starting while loop to run the app or quit while_quit = 0 while while_quit == 0: # asks if the user wants to see it's favorites or to search new products choice = user_choice() if choice == 2: new_search(user) else: favorites_search(user) # going out of while loop. quit_options = [{ 'selector': 'o', 'prompt': 'oui', 'return': 0 }, { 'selector': 'n', 'prompt': 'non', 'return': 1 }] while_quit = prompt.options("Souhaitez-vous continuer ?", quit_options)
def _do_turn(round_): player = round_.current_hand.player puts() _puts_player_header(player) puts() if round_.is_terminal: _puts_round_is_terminal_warning(round_) puts() _puts_formatted_hand(round_.current_hand) _draw_action = prompt.options('What would you like to do?', [ { 'selector': str(DrawAction.ACTION_TAKE), 'prompt': 'Take the %s from the discard pile' % colored.green(str(round_.last_discard)) }, { 'selector': str(DrawAction.ACTION_DRAW), 'prompt': 'Draw a card' }, ], default=str(DrawAction.ACTION_DRAW)) draw_action = DrawAction(round_, _draw_action) card = draw_action() if draw_action.action == DrawAction.ACTION_DRAW: puts('Drew a ', newline=False) puts(colored.green(str(card))) _card_action = prompt.options( 'What would you like to do with the %s?' % colored.green(str(card)), CARD_DRAW_ACTIONS, default=str(CardAction.ACTION_DISCARD), ) else: _card_action = prompt.options( 'What would you like to do with the %s?' % colored.green(str(card)), CARD_TAKE_ACTIONS) CardAction(round_, _card_action)(card) round_.end_turn()
def update_device(): ''' Updates device \'filled\' attribute ''' payload = dict() payload['id'] = prompt.query('Enter device ID') payload['filled'] = prompt.options('Filled?', options=[ {'selector': 'Y', 'prompt': 'Yes', 'return': 1}, {'selector': 'N', 'prompt': 'No', 'return': 0} ]) send_request('put', payload)
def setup_user_input(): config_file = prompt.query('Config file name:', default='local') config_class = prompt.query('Config class name:', default='LocalConfig') test_schema = prompt.options('Which tests do you want to run?', triple_options) _dict = { 'config_file': config_file.lower(), 'config_class': config_class, 'test_schema': test_schema } return _dict
def create(): ''' Create a new device and record attributes in database ''' payload = dict() lat = prompt.query('Enter latitude:\n>> ') lng = prompt.query('Enter longitude:\n>> ') payload['type'] = prompt.options('Enter bin type', options=[ { 'selector': 1, 'prompt': 'paper', 'return': 'paper' }, { 'selector': 2, 'prompt': 'metal', 'return': 'metal' }, { 'selector': 3, 'prompt': 'normal', 'return': 'normal' }, { 'selector': 4, 'prompt': 'plastic', 'return': 'plastic' }, { 'selector': 5, 'prompt': 'glass', 'return': 'glass' }, ]) payload['district'] = prompt.options( 'Enter District', options=[{ 'selector': i, 'prompt': district, 'return': district } for i, district in enumerate(district_list)]) payload['lat'] = lat if lat[0] != 'n' else '-' + lat[1:] payload['lng'] = lng if lng[0] != 'n' else '-' + lng[1:] send_request('post', payload)
def setupBoard(inital=True): global portSelection if inital == True: boards = serialPorts() boardOption = prompt.options("Select Device:", boards) portSelection = boards[boardOption - 1] baudRate, library = getConfig() commandList = [{ 'selector': '1', 'prompt': 'Get ID' }, { 'selector': '2', 'prompt': 'Get PAC' }, { 'selector': '3', 'prompt': 'Get Library Version' }, { 'selector': '4', 'prompt': 'Send Message' }, { 'selector': '5', 'prompt': 'Custom Command' }, { 'selector': '6', 'prompt': 'Config' }, { 'selector': '0', 'prompt': 'Exit' }] command = int(prompt.options("Command:", commandList)) if command == 0: print "Exiting program..." sys.exit(0) if command != 6: puts(colored.blue('Initialising {0}'.format(portSelection))) device = Sigfox(portSelection, baudRate, library) device.handleCommand(command)
def create(): ''' Create a new device and record attributes in database ''' payload = dict() lat = prompt.query('Enter latitude:\n>> ') lng = prompt.query('Enter longitude:\n>> ') payload['type'] = prompt.options('Enter bin type', options=[ {'selector': 1, 'prompt': 'paper', 'return': 'paper'}, {'selector': 2, 'prompt': 'metal', 'return': 'metal'}, {'selector': 3, 'prompt': 'normal', 'return': 'normal'}, {'selector': 4, 'prompt': 'plastic', 'return': 'plastic'}, {'selector': 5, 'prompt': 'glass', 'return': 'glass'}, ]) payload['district'] = prompt.options('Enter District', options=[ {'selector': i, 'prompt': district, 'return': district} for i, district in enumerate(district_list) ]) payload['lat'] = lat if lat[0] != 'n' else '-'+lat[1:] payload['lng'] = lng if lng[0] != 'n' else '-'+lng[1:] send_request('post', payload)
def start(self): # 执行文档处理过程,处理结束后保存 for block in self.iter_block_items(self.document): if isinstance(block, Paragraph): self.process_paragraph(block) elif isinstance(block, Table): self.process_table(block) inst_options = [{ 'selector': '1', 'prompt': '确认保存', 'return': False }, { 'selector': '2', 'prompt': '退出/不保存', 'return': True }] puts(colored.yellow('=' * 50)) quit = prompt.options('以上内容将发生改变,请确认:', inst_options) if quit: puts(colored.green('变更未作保存。')) exit(0) while True: try: self.document.save(self.file) # 保存处理完毕的文件 puts(colored.red('变更已保存。')) exit(0) except PermissionError as e: print(e) inst_options = [{ 'selector': '1', 'prompt': '重试', 'return': False }, { 'selector': '2', 'prompt': '退出/不保存', 'return': True }] quit = prompt.options('文件是否已经打开?请关闭后重试。', inst_options) if quit: exit(0)
def choose_from_list(file_list, message): options = [] for i, file_name in enumerate(file_list, start=1): options.append({ 'selector': i, 'prompt': f'{file_name}', 'return': file_name }) key = prompt.options(message, options) puts(colored.blue(f'You selected {key}')) return key
def _choose_sub(config): sub_names = config.get_subs() if sub_names is None: return subscription_options = [] pad_num = len(str(len(sub_names))) for i, sub_name in enumerate(sub_names): subscription_options.append( {"selector": str(i + 1).zfill(pad_num), "prompt": sub_name, "return": i}) return prompt.options("Choose a subscription:", subscription_options)
def send_message(sess): friends = sess.get_friends() options = [{ 'selector': i, 'prompt': friends[j], 'return': j } for i, j in enumerate(friends.keys())] uid = prompt.options("select friend:", options) message = prompt.query("text: ") sess.send_message(uid, message)
def remove_data(): to_remove = prompt.options('Enter corporation symbol:', get_company_options()) if not to_remove: puts('Exited') elif to_remove == '*': Stock.delete().execute() puts('All records removed') else: num_removed = 0 records = Stock.select().join(Company).where(Stock.company == to_remove) for record in records: num_removed += record.delete_instance() puts('Cleared {:d} records from {:s}'.format(num_removed, to_remove))
def _choose_sub(conf: config.Config) -> int: sub_names = conf.get_subs() subscription_options = [] pad_num = len(str(len(sub_names))) for i, sub_name in enumerate(sub_names): subscription_options.append({ "selector": str(i + 1).zfill(pad_num), "prompt": sub_name, "return": i }) return prompt.options("Choose a subscription:", subscription_options)
def list_bucket(session, bucket): s3 = session.client('s3') if not bucket: buckets = s3.list_buckets() options = [b['Name'] for b in buckets['Buckets']] bucket = prompt.options('Please pick a bucket', options) files = s3.list_objects_v2(Bucket=options[bucket - 1]) for file in files['Contents']: puts( columns( [colored.green(file['Key']), 60], [colored.red(str(file['Size'])), 25], ))
def create_stack(stack_name): ec2_type_options = [{ 'selector': '1', 'prompt': 't2.small', 'return': 't2.small' }, { 'selector': '2', 'prompt': 't2.xlarge', 'return': 't2.xlarge' }, { 'selector': '3', 'prompt': 'p2.xlarge', 'return': 'p2.xlarge' }, { 'selector': '4', 'prompt': 'p3.2xlarge', 'return': 'p3.2xlarge' }] ec2_type = prompt.options("What type of ec2 instance", ec2_type_options) puts(colored.cyan(f'You chose {ec2_type}')) template = get_template() image_id = 'ami-2fa95952' # Ubuntu nvidia-docker print(template) print(stack_name) my_keys = list_keypairs() key = choose_from_list(my_keys, 'Which key?') response = cf_client.create_stack(StackName=stack_name, TemplateBody=json.dumps(template), Parameters=[{ 'ParameterKey': 'MyIdentifier', 'ParameterValue': stack_name }, { 'ParameterKey': 'MyImageId', 'ParameterValue': image_id }, { 'ParameterKey': 'InstanceType', 'ParameterValue': ec2_type }, { 'ParameterKey': 'KeyName', 'ParameterValue': key, 'UsePreviousValue': True }]) puts( colored.green( f'Creating stack {stack_name} with a {ec2_type} instance'))
def list_bucket(session, bucket): s3 = session.client('s3') if not bucket: buckets = s3.list_buckets() options = [b['Name'] for b in buckets['Buckets']] bucket = prompt.options('Please pick a bucket', options) files = s3.list_objects_v2(Bucket=options[bucket-1]) for file in files['Contents']: puts( columns( [colored.green(file['Key']), 60], [colored.red(str(file['Size'])), 25], ) )
def remove_company(): sym = prompt.options('Enter corporation name/symbol:', get_company_options()) if not sym: puts('Exited') elif sym == '*': Company.delete().execute() Stock.delete().execute() puts('All companies removed') else: for company in Company.select(Company, Stock).join(Stock).where(Stock.company == Company.id): for stock in company.company_stock: stock.delete_instance() if sym in company.id or sym in company.name: puts("'{:s}' deleted".format(company.name)) company.delete_instance()
def update_device(): ''' Updates device \'filled\' attribute ''' payload = dict() payload['id'] = prompt.query('Enter device ID') payload['filled'] = prompt.options('Filled?', options=[{ 'selector': 'Y', 'prompt': 'Yes', 'return': 1 }, { 'selector': 'N', 'prompt': 'No', 'return': 0 }]) send_request('put', payload)
def choose_stack(): stacks = cf_client.list_stacks()['StackSummaries'] options = [] idx = 1 for stack in stacks: if stack['StackStatus'] != 'DELETE_COMPLETE': options.append({ 'selector': idx, 'prompt': stack['StackName'], 'return': stack['StackName'] }) idx += 1 selected_stack = prompt.options("Which stack", options) puts(colored.blue(f'You selected {selected_stack}')) return selected_stack
def _read(self): inst_options = list() for idx, fun in enumerate(self._function_list): option = dict() option["selector"] = str(idx) option["prompt"] = '%s : %s' % (fun["name"], fun["description"]) option["return"] = fun inst_options.append(option) select_fun = prompt.options("Select a function", inst_options) for idx, arg in enumerate(select_fun["args"]): arg[2] = self._get_arg_value(arg) return select_fun
def examples(): """ Procedure for choosing and running example """ keep_asking = True while keep_asking: verticalLine() example = prompt.options( colored.magenta("What would you like to try out?"), example_menu) if (example == "ca"): changeColorAll() elif (example == "cs"): changeColorSpecific() elif (example == "exit"): keep_asking = False else: puts(colored.yellow("Wrong input, try again"))
def main(): verticalLine() puts("Welcome to EENX15-1919 UART test interface!") while True: verticalLine() action = prompt.options(colored.magenta("What would you like to do?"), main_menu) if (action == "s"): send() elif (action == "r"): recieve() elif (action == "exit"): ser.close() exit() else: wrong_input
def dataSetsMenu(dataSets): putSeparator() puts("Current Data Sets:") with indent(4): printDataSets(dataSets) putSeparator('-', 30) menuOptions = [{ 'selector': '1', 'prompt': 'Modify Data Sets' }, { 'selector': '2', 'prompt': 'Back to Main Menu' }] return prompt.options('Data Sets Menu:', menuOptions, default='1')
def update_stack(stack_name): ec2_type_options = [{ 'selector': '1', 'prompt': 't2.small', 'return': 't2.small' }, { 'selector': '2', 'prompt': 't2.medium', 'return': 't2.medium' }, { 'selector': '3', 'prompt': 't2.xlarge', 'return': 't2.xlarge' }, { 'selector': '4', 'prompt': 'p2.xlarge', 'return': 'p2.xlarge' }] ec2_type = prompt.options("Which stack?", ec2_type_options) puts(colored.cyan(f'You chose {ec2_type}')) template = get_template() image_id = 'ami-2fa95952' # Ubuntu nvidia-docker response = cf_client.update_stack(StackName=stack_name, TemplateBody=json.dumps(template), Parameters=[{ 'ParameterKey': 'MyIdentifier', 'ParameterValue': stack_name }, { 'ParameterKey': 'MyImageId', 'ParameterValue': image_id }, { 'ParameterKey': 'InstanceType', 'ParameterValue': ec2_type }, { 'ParameterKey': 'KeyName', 'ParameterValue': 'sj-mac-2017' }]) puts( colored.green( f'Creating stack {stack_name} with a {ec2_type} instance'))
def list_data(): company = prompt.options('Enter corporation symbol:', get_company_options()) if not company: puts('Exited') return elif company == '*': stocks_data = Stock.select() else: stocks_data = Stock.select().join(Company).where(Stock.company == company) if not stocks_data: puts('No stock records found') else: puts('Company :: P/E ratio :: Ask price :: Day High :: Day Low :: Revenue :: Timestamp') for stock in stocks_data: puts('{0} | {1} | {2} | {3} | {4} | {5} | {6}'.format( stock.company.name, stock.pe_ratio,stock.ask_price, stock.day_high, stock.day_low, stock.revenue, stock.timestamp ))
def choose_ec2(attr='InstanceId'): response = ec2_client.describe_instances() ec2_type_options = [] for i, reservation in enumerate(response["Reservations"], start=1): for j, instance in enumerate(reservation["Instances"], start=1): instance_id = instance["InstanceId"] state = instance["State"]["Name"] # print(instance) instance_name = get_instance_name(instance) ec2_type_options.append({ 'selector': i, 'prompt': f'{instance_name} / {instance_id} / {instance["InstanceType"]} / {state}', 'return': instance }) selected_instance = prompt.options("Which ec2 instance", ec2_type_options) puts(colored.blue(f'You selected {selected_instance["InstanceId"]}')) return selected_instance
def mainMenu(totalDataSets, settings): editSettingsPrompt = "Edit Settings(Min: %(min)f, Max: %(max)f, Method: %(method)s, Smooth: %(smooth)d, POrder: %(porder)d, Max It: %(max_it)d, Precision: %(prec)d)" % settings menuOptions = [{ 'selector': '1', 'prompt': "Data Sets(Total: %d)" % totalDataSets }, { 'selector': '2', 'prompt': editSettingsPrompt }, { 'selector': '3', 'prompt': 'Reset Settings to Default' }, { 'selector': '4', 'prompt': 'Process Data Sets' }, { 'selector': '5', 'prompt': 'Quit Sab Spectra' }] putSeparator() return prompt.options('Main Menu:', menuOptions, default='4')
def opencfl_log(profile, bucket, distribution, prefix, year, month, day): session = boto3.Session(profile_name=profile) s3_client = session.client('s3') # create a prefix based on distribution, year and month prefix = prefix + '/' + distribution if year: prefix += '.' + str(year) if month: prefix += '-' + str(month) if day: prefix += '-' + str(day) files = s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix) options = [k['Key'] for k in files['Contents']] try: filename = prompt.options('Pick log to view', [o.split('/')[1] for o in options]) except KeyboardInterrupt: quit(0) s3obj = s3_client.get_object(Bucket=bucket, Key=options[filename-1]) with gzip.open(s3obj['Body'], 'rt') as f: responses = parse(f.readlines()) puts( columns( [colored.yellow('method'), 6], [colored.yellow('status'), 6], [colored.yellow('result'), 10], [colored.yellow('timestamp'), 20], [colored.yellow('request_id'), 56], [colored.yellow('path'), None], ) ) for r in responses: puts( columns( [colored.green(r.http_method), 6], [colored.red(r.status_code), 6], [colored.red(r.edge_result_type), 10], [colored.cyan(arrow.get(r.timestamp).to('US/Eastern').humanize()), 20], [colored.yellow(r.request_id), 56], [colored.blue(r.path), None], ) )
def clean(dups): puts( blue('we have founded ') + red(str(len(dups))) + blue(' duplications')) inst_options = [{ 'selector': '1', 'prompt': 'please review', 'return': 'y' }, { 'selector': '2', 'prompt': 'better in other moment', 'return': 'n' }] willContinue = prompt.options(green('Do you want to continue?'), inst_options) if willContinue == 'y': generator = cleanDuplicated(dups) for i in dups: next(generator) # next(cleanDuplicated(dups)) else: print('quuyerioyurti')
def run(): try: load_defaults() click.clear() # main loop while True: choice = prompt.options("What would you like to do?: ", [ "Find live match of default summoner", "Find live match of another summoner", "Change default region", "Change default summoner", "Quit" ]) if choice == 5: break else: commands[choice - 1]() time.sleep(2) # delay before terminal clear # click.clear() except (KeyboardInterrupt, click.exceptions.Abort): pass finally: click.echo("\nThanks for using liveleague!")
puts( colored.green( "You will need the following pieces of information to proceed safely:") ) puts("FQDN") puts("Content Root") readyOptions = [{ 'selector': '0', 'prompt': 'No {will exit immediately}', 'return': False }, { 'selector': '1', 'prompt': 'Yes', 'return': True }] ready = prompt.options("Are you prepared?", readyOptions) if (ready): puts( colored.red( "OK. Enter '.' at any non-option prompt to exit without saving.")) print("OK") fqdn = prompt.query("What is the FQDN? :") if (fqdn == '.'): sys.exit(0) proposedContentRoot = prompt.query( "What is the content root for {} [e.g., /content/foo/en/]".format( fqdn)) if (proposedContentRoot == '.'): sys.exit(0)
content = '' bar = pyprind.ProgBar(file_size/1024, title='CVXNorm Codes') for chunk in r.iter_content(chunk_size=1024, decode_unicode=True): if chunk: content += chunk bar.update() def sizeof_fmt(num, suffix='B'): for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def main(): download() if __name__ == '__main__': name = prompt.query('Where is your database?') inst_options = [{'selector': '1', 'prompt': 'Full', 'return': 'full'}, {'selector': '2', 'prompt': 'Partial', 'return': 'partial'}, {'selector': '3', 'prompt': 'None', 'return': 'no install'}] inst = prompt.options("Full or Partial Install", inst_options) main()
def start(self, jobs, path_format): checksum_files = [] pgp_public_keys = {} for job in jobs: file_list = None if "sha1" in job.checksum_file: file_list = job.checksum_file["sha1"] elif "md5" in job.checksum_file: file_list = job.checksum_file["md5"] elif "sha256" in job.checksum_file: file_list = job.checksum_file["sha256"] else: print("No checksums available for {}".format(job.label)) if file_list: if not isinstance(file_list, list): file_list = [file_list] for file in file_list: if (file, False) not in checksum_files: checksum_files.append((file, False)) if job.pgp_suffix: checksum_files.append(("{}{}".format(file, job.pgp_suffix), True)) pgp_public_keys[file] = { 'id': job.pgp_key_id, 'keyserver': job.pgp_keyserver } cache_dir = xdg.BaseDirectory.save_cache_path('iso-manager') checksum_cache_dir = os.path.join(cache_dir, "checksums") if not os.path.isdir(checksum_cache_dir): os.mkdir(checksum_cache_dir) with progress.Bar(label="Downloading checksum files", expected_size=len(checksum_files), hide=False) as bar: bar.show(0) index = 0 for file in checksum_files: file_id = hashlib.sha1(file[0].encode('utf-8')).hexdigest() target_path = os.path.join(checksum_cache_dir, file_id) if not os.path.isfile(target_path): urllib.request.urlretrieve(file[0], target_path) index += 1 bar.show(index) with progress.Bar(label="Verifying PGP signatures", expected_size=len(checksum_files) / 2, hide=False) as bar: bar.show(0) index = 0 for file in checksum_files: if file[1]: # This is a signature file checksum_for = '.'.join(file[0].split('.')[0:-1]) file_id = hashlib.sha1(checksum_for.encode('utf-8')).hexdigest() checksum_file_id = hashlib.sha1(file[0].encode('utf-8')).hexdigest() checksum_file = os.path.join(checksum_cache_dir, file_id) signature_file = os.path.join(checksum_cache_dir, checksum_file_id) result = subprocess.call(["gpg", "--verify", signature_file, checksum_file], stderr=subprocess.DEVNULL) pgp_info = pgp_public_keys[checksum_for] if result == 2: print("\nSignature could not be verified for {}".format(checksum_for)) options = [ { 'selector': '1', 'prompt': 'Download the public key {id} from {keyserver}'.format(**pgp_info), 'return': 'download' }, { 'selector': '2', 'prompt': "Don't check the signature for the checksum file", 'return': 'ignore' }, { 'selector': '3', 'prompt': 'Abort verifying altogether', 'return': 'abort' } ] ask = prompt.options("Do you want to download the public key {}?".format(pgp_info['id']), options) if ask == 'download': subprocess.call(['gpg', '--keyserver', pgp_info['keyserver'], '--recv-keys', '0x{}'.format(pgp_info['id'])]) elif result == 1: print("\n\nSignature invalid for {}. Aborting.".format(checksum_for)) exit(1) index += 1 bar.show(index) with progress.Bar(label="Verifying checksums", expected_size=len(jobs), hide=False) as bar: bar.show(0) index = 0 for job in jobs: iso_file = job.get_path(path_format) if os.path.isfile(iso_file): if "sha1" in job.checksum_file: file_list = job.checksum_file["sha1"] algorithm = "sha1" elif "md5" in job.checksum_file: file_list = job.checksum_file["md5"] algorithm = "md5" elif "sha256" in job.checksum_file: file_list = job.checksum_file["sha256"] algorithm = "sha256" else: raise Exception("No hash key found") if not isinstance(file_list, list): file_list = [file_list] hashes = {} for file in file_list: cache_id = hashlib.sha1(file.encode('utf-8')).hexdigest() checksum_file = os.path.join(checksum_cache_dir, cache_id) hashes.update(self.parse_hash_file(checksum_file)) file_hash = self.file_hash(algorithm, iso_file) if file_hash != hashes[job.get_filename_for_checksum()]: print("Checksum invalid for {}. Aborting.".format(job.label)) exit(1) index += 1 bar.show(index)
def main() -> None: """Run puckfetcher on the command line.""" global LOG log_dir = constants.APPDIRS.user_log_dir log_filename = os.path.join(log_dir, f"{__package__}.log") LOG = util.set_up_logging(log_filename=log_filename, verbosity=constants.VERBOSITY) parser = _setup_program_arguments() args = parser.parse_args() (cache_dir, config_dir, data_dir) = _setup_directories(args) try: conf = config.Config(config_dir=config_dir, cache_dir=cache_dir, data_dir=data_dir) except error.MalformedConfigError as exception: LOG.error("Unable to start puckfetcher - config error.") LOG.error(exception.desc) parser.exit() args = parser.parse_args() command_options = [] config_commands = config.get_commands() for i, key in enumerate(config_commands): value = config_commands[key] command_options.append({ "selector": str(i + 1), "prompt": value, "return": key.name }) # See if we got a command-line command. config_dir = vars(args)["config"] command = vars(args)["command"] if command: if command == "menu": pass else: if command != "exit": _handle_command(command, conf) parser.exit() LOG.info(f"{__package__} {constants.VERSION} started!") while True: try: command = prompt.options("Choose a command", command_options) if command == "exit": parser.exit() _handle_command(command, conf) # TODO look into replacing with # https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python except KeyboardInterrupt: LOG.critical("Received KeyboardInterrupt, exiting.") break except EOFError: LOG.critical("Received EOFError, exiting.") break parser.exit()
def setup_user_input(): """ Setup configuration and database loading script by querying information from user. """ print( "#### Please answer the following questions to setup the folder ####") log_folder = prompt.query('Logging folder (must exist):', default='.', validators=[validators.PathValidator()]) loader_file = prompt.query('Loader file name:', default='loader') config_file = prompt.query('Config file name:', default='local') config_class = prompt.query('Config class name:', default='LocalConfig') print("#### Database configuration setup ####") dialect = prompt.options('Marcotti-Events Database backend:', dialect_options) if dialect == 'sqlite': dbname = prompt.query('Database filename (must exist):', validators=[validators.FileValidator()]) dbuser = '' hostname = '' dbport = 0 else: dbname = prompt.query('Database name:') dbuser = prompt.query('Database user:'******'') puts( colored.red( 'Database password is not defined -- You must define it in the config file!' )) hostname = prompt.query('Database hostname:', default='localhost') dbport = prompt.query('Database path:', default=db_ports.get(dialect)) print("#### Database season setup ####") start_yr = prompt.query('Start season year', default='1990', validators=[validators.IntegerValidator()]) end_yr = prompt.query('End season year', default='2020', validators=[validators.IntegerValidator()]) print("#### Data file setup ####") supplier = prompt.query('Name of data supplier:') is_club_db = prompt.options('Is this a club database?', binary_options) spanish = prompt.options('Are country names in Spanish?', binary_options) csv_data_dir = prompt.query('Directory containing CSV data files:', default='.', validators=[validators.PathValidator()]) supplier_data_path = path_query( 'Relative path of Suppliers CSV data files:') club_data_path = path_query('Relative path of Clubs CSV data files:') comp_data_path = path_query( 'Relative path of Competitions CSV data files:') season_data_path = path_query('Relative path of Seasons CSV data files:') venue_data_path = path_query('Relative path of Venues CSV data files:') position_data_path = path_query( 'Relative path of Player Positions CSV data files:') player_data_path = path_query('Relative path of Players CSV data files:') manager_data_path = path_query('Relative path of Managers CSV data files:') referee_data_path = path_query('Relative path of Referees CSV data files:') league_match_data_path = path_query( 'Relative path of League Matches CSV data files:') group_match_data_path = path_query( 'Relative path of Group Matches CSV data files:') knockout_match_data_path = path_query( 'Relative path of Knockout Matches CSV data files:') goal_data_path = path_query('Relative path of Goals CSV data files:') penalty_data_path = path_query( 'Relative path of Penalties CSV data files:') bookable_data_path = path_query( 'Relative path of Bookables CSV data files:') substitution_data_path = path_query( 'Relative path of Substitutions CSV data files:') shootout_data_path = path_query( 'Relative path of Penalty Shootouts CSV data files:') player_stats_data_path = path_query( 'Relative path of Player Statistics CSV data files:') print("#### End setup questions ####") setup_dict = { 'loader_file': loader_file.lower(), 'config_file': config_file.lower(), 'config_class': config_class, 'supplier': supplier, 'dialect': dialect, 'dbname': dbname, 'dbuser': dbuser, 'dbhost': hostname, 'dbport': dbport, 'start_yr': start_yr, 'end_yr': end_yr, 'logging_dir': log_folder, 'log_file_path': os.path.join(log_folder, 'marcotti.log'), 'club_db': is_club_db, 'country_prefix': 'es' * (spanish is True), 'csv_data_dir': csv_data_dir, 'csv_data': { 'suppliers': supplier_data_path, 'competitions': comp_data_path, 'seasons': season_data_path, 'clubs': club_data_path, 'venues': venue_data_path, 'positions': position_data_path, 'players': player_data_path, 'managers': manager_data_path, 'referees': referee_data_path, 'league_matches': league_match_data_path, 'group_matches': group_match_data_path, 'knockout_matches': knockout_match_data_path, 'goals': goal_data_path, 'penalties': penalty_data_path, 'bookables': bookable_data_path, 'substitutions': substitution_data_path, 'shootouts': shootout_data_path, 'statistics': player_stats_data_path } } return setup_dict
def main(): """Run puckfetcher on the command line.""" parser = _setup_program_arguments() args = parser.parse_args() (cache_dir, config_dir, data_dir, log_dir) = _setup_directories(args) # pylint: disable=invalid-name LOG = _setup_logging(log_dir) try: config = Config.Config(config_dir=config_dir, cache_dir=cache_dir, data_dir=data_dir) except Error.MalformedConfigError as exception: LOG.error("Unable to start puckfetcher - config error.") LOG.error(exception) parser.exit() index = 1 command_options = [{"selector": str(index), "prompt": "Exit.", "return": "exit"}] index += 1 config_commands = config.get_commands() for key in config_commands: value = config.commands[key] command_options.append({"selector": str(index), "prompt": value, "return": key.name}) index += 1 # See if we got a command-line command. config_dir = vars(args)["config"] command = vars(args)["command"] if command: if command == "exit": parser.exit() elif command == "menu": pass else: _handle_command(command, config, command_options, LOG) parser.exit() LOG.info("%s %s started!", __package__, CONSTANTS.VERSION) while True: try: command = prompt.options("Choose a command", command_options) if command == "exit": parser.exit() _handle_command(command, config, command_options, LOG) # TODO look into replacing with # https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python except KeyboardInterrupt: LOG.critical("Received KeyboardInterrupt, exiting.") break except EOFError: LOG.critical("Received EOFError, exiting.") break parser.exit()
'selector': 'r', 'prompt': 'Remove printer', 'return': 'r' }, { 'selector': 'u', 'prompt': 'Update printer', 'return': 'u' }, { 'selector': 'exit', 'prompt': 'Exit program', 'return': 'exit' }] while True: verticalLine() action = prompt.options(colored.magenta("What would you like to do?"), main_menu) if (action == "e"): examples() elif (action == "s"): showPrinters() elif (action == "a"): addPrinter() elif (action == "r"): removePrinter() elif (action == "u"): updatePrinters() elif (action == "exit"): exit() else: wrong_input
def main(): while True: podcast_search = prompt.query("Podcast you want to download: ") clear() podcast_search = re.sub(r" ", "+", podcast_search) url = "https://itunes.apple.com/search?term=" + podcast_search + "&entity=podcast" data = get_data(url) result_count = int(data["resultCount"]) if result_count <= 0: puts('No results found, please search again') continue puts("{:d} results were found. Displaying the top ten now".format(result_count)) for i in range(result_count): puts("{:d}: {:s}".format( i + 1, data["results"][i]["trackName"] )) if len(data["results"][i]["artistName"]) > 40: data["results"][i]["artistName"] = data["results"][i]["artistName"][0:40]+'...' puts("\tArtist: {:s}".format( data["results"][i]["artistName"] )) puts() user_selection = int(prompt.query("Enter podcast number (0 if None): ", validators=[ validators.IntegerValidator() ])) clear() if user_selection == 0: raise SystemExit('Goodbye!') elif 0 < user_selection <= result_count: podcast_name = data["results"][user_selection - 1]["trackName"] podcast_id = data["results"][user_selection - 1]["collectionId"] puts("You have selected {:s}".format(podcast_name)) break else: puts("Incorrect number, please search again.") url = "https://itunes.apple.com/lookup?id=" + str(podcast_id) + "&entity=podcast" data = get_data(url) rss_url = data["results"][0]["feedUrl"] data_root = feedparser.parse(get_data(rss_url, json=False))['entries'] enclosures = [entry.enclosures[0].href for entry in data_root] titles = [entry.title for entry in data_root] ext = re.search(r'\.\w+?$', enclosures[0]).group(0) mp3list = [] for link in enclosures: mp3list.append(link) num_titles = len(titles) puts("{:d} titles found, printing the latest 10...".format(num_titles)) for i in range(min(10, len(titles))): puts('[{:d}] {:s}'.format(i+1, titles[i].strip('\n'))) puts() download_all = False download_one = -1 download_new = False; download_range_start = -1 download_range_finish = -1 bad_input = True while bad_input: bad_input = False if bad_input: puts('Error: bad input') user_download = prompt.options('Select download options ', options=[ 'All', 'Latest', 'Specific file', 'Range' ]) clear() if user_download == 1: download_all = True elif user_download == 2: download_new = True elif user_download == 3: user_download = prompt.query('Enter file number', validators=[ validators.IntegerValidator() ]) clear() if 0 < user_download < 11: download_one = len(mp3list) - int(user_download) + 1 else: bad_input = True continue else: user_download = prompt.query('Enter file range (ex: 1 - 3)') clear() if '-' in user_download: try: range_list = [int(num.strip()) for num in user_download.split('-')] except ValueError: bad_input = True continue download_range_start = len(mp3list) - int(range_list[1]) download_range_finish = len(mp3list) - int(range_list[0]) if len(range_list) != 2 or not (0 < download_range_start < download_range_finish < 11): bad_input = True continue else: bad_input = True continue break base_path = os.path.dirname(os.path.realpath(__file__)) if download_all: for i in range(len(mp3list)): puts("Downloading: {:s}".format(titles[i])) save_loc = "{:s}/{:s}{:s}".format( base_path, titles[i], ext ) geturl(mp3list[i], save_loc) puts() elif download_one >= 0: puts("Downloading: {:s}".format(titles[int(download_one)])) save_loc = "{:s}/{:s}{:s}".format( base_path, titles[int(download_one)], ext ) geturl(mp3list[int(download_one)], save_loc) elif download_new: puts("Downloading: {:s}".format(titles[0])) save_loc = "{:s}/{:s}{:s}".format( base_path, titles[0], ext ) geturl(mp3list[int(download_one)], save_loc) else: for i in range(download_range_start, download_range_finish + 1): puts("Downloading: {:s}".format(titles[i])) save_loc = "{:s}/{:s}{:s}".format( base_path, titles[i], ext ) geturl(mp3list[i], save_loc) puts() puts('Process Complete')
def setup_user_input(): """ Setup configuration and database loading script by querying information from user. :return: """ print "#### Please answer the following questions to setup the folder ####" log_folder = prompt.query('Logging folder (must exist):', default='.', validators=[validators.PathValidator()]) loader_file = prompt.query('Loader file name:', default='loader') config_file = prompt.query('Config file name:', default='local') config_class = prompt.query('Config class name:', default='LocalConfig') print "#### Database configuration setup ####" dialect = prompt.options('Marcotti-MLS Database backend:', dialect_options) if dialect == 'sqlite': dbname = prompt.query('Database filename (must exist):', validators=[validators.FileValidator()]) dbuser = '' hostname = '' dbport = 0 else: dbname = prompt.query('Database name:') dbuser = prompt.query('Database user:'******'') puts(colored.red('Database password is not defined -- You must define it in the config file!')) hostname = prompt.query('Database hostname:', default='localhost') dbport = prompt.query('Database path:', default=db_ports.get(dialect)) print "#### Database season setup ####" start_yr = prompt.query('Start season year', default='1990', validators=[validators.IntegerValidator()]) end_yr = prompt.query('End season year', default='2020', validators=[validators.IntegerValidator()]) print "#### Data file setup ####" top_level_data_dir = prompt.query('Directory containing CSV data files:', default='.', validators=[validators.PathValidator()]) club_data_path = path_query('Relative path of Clubs data files:') comp_data_path = path_query('Relative path of Competitions data files:') comp_season_data_path = path_query('Relative path of CompetitionSeasons data files:') player_data_path = path_query('Relative path of Players data files:') acq_data_path = path_query('Relative path of Player Acquisitions data files:') salary_data_path = path_query('Relative path of Salaries data files:') partial_data_path = path_query('Relative path of Partial Tenure data files:') minutes_data_path = path_query('Relative path of Player Minutes data files:') field_stat_data_path = path_query('Relative path of Field Player Statistics data files:') gk_stat_data_path = path_query('Relative path of Goalkeeper Statistics data files:') points_data_path = path_query('Relative path of League Points data files:') print "#### End setup questions ####" setup_dict = { 'loader_file': loader_file.lower(), 'config_file': config_file.lower(), 'config_class': config_class, 'dialect': dialect, 'dbname': dbname, 'dbuser': dbuser, 'dbhost': hostname, 'dbport': dbport, 'start_yr': start_yr, 'end_yr': end_yr, 'logging_dir': log_folder, 'log_file_path': os.path.join(log_folder, 'marcotti.log'), 'data_dir': top_level_data_dir, 'data': { 'clubs': club_data_path, 'competitions': comp_data_path, 'comp_seasons': comp_season_data_path, 'players': player_data_path, 'acquisitions': acq_data_path, 'salaries': salary_data_path, 'partials': partial_data_path, 'minutes': minutes_data_path, 'field_stats': field_stat_data_path, 'gk_stats': gk_stat_data_path, 'points': points_data_path } } return setup_dict