def process(self): self.pull() answers = self.parseInput() summary = f""" provincia: {answers['provincia']} fecha: {answers['dia']}/{answers['mes']}/{answers['año']} confirmados: {answers['confirmados']} muertes: {answers['muertes']} recuperados: {answers['recuperados']} """ print("Estas por ingresar:") print(summary) confirm = inquirer.prompt( [inquirer.Confirm('yes', message='Desea continuar?')]) if confirm["yes"]: print("Actualizando csv...") self.updateCsv(answers) self.commit(summary) else: print("Abortando entrada actual.") another = inquirer.prompt([ inquirer.Confirm('yes', message='Desea cargar otra provincia continuar?') ]) if another["yes"]: self.process() else: print("Subiendo archivo...") self.push() print("Listo!")
def triage(ctx): while True: tasklist = ctx.obj['API'].all_tasks(mode='triage') mychoice = taskchoice(tasklist) print(mychoice.export()) # TODO current values as defaults questions = [inquirer.Confirm('important', message='Is it important?'), inquirer.Confirm('urgent', message='Is it urgent?'), inquirer.Text('pomodoros', message='How many poms?')] # TODO validate answers = inquirer.prompt(questions) answers['pomodoros'] = int(answers['pomodoros']) mychoice.update(answers) print(mychoice.export())
def one_for_all(to_convert, to_save): questions = [ inquirer.Path("palette", path_type=inquirer.Path.FILE, message="What file will be the palette?", default="assets/cobblestone.png"), inquirer.Confirm("brightness", message="Map brightness?"), inquirer.Confirm("transparency", message="Map transparency?"), inquirer.Confirm("color", message="Map color?") ] answers = inquirer.prompt(questions) one.all_one(answers['palette'], to_convert, to_save, answers['brightness'], answers['transparency'], answers['color'])
def cancel(): """Cancel class""" username = input("CNS ID: ") password = getpass("CNS Password: "******"\tperiod " + course[1] + "\t" + course[2]) for course in registered_class] course_to_cancel = inquirer.prompt([ inquirer.List('course', message='Please choose the class you want to cancel', choices=courses_name) ]) selected = course_to_cancel["course"].split("\t") comfirm = inquirer.prompt([ inquirer.Confirm( 'continue', message=("You selected " + selected[2] + " on " + selected[0] + " " + selected[1] + ". Cancel it?")) ]) if comfirm["continue"]: bot.cancel_class(selected[0], selected[1][-1], selected[2]) bot.tear_down() elif not comfirm["continue"]: bot.tear_down() sys.exit()
def action_build_pwa(): print(build_pwa) # If an app is being deployed to other channels # such as Cordova or Electron, you can # remove the "serviceWorker": true flag # from the angular.json file. # The service worker can be generated by running: # ionic build --prod --service-worker cmd = 'ionic build --prod' questions = [ inquirer.Confirm('use_service_worker', message='Soll für Electron oder Cordova gebaut werden?', default=False) ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) use_service_worker = answers['use_service_worker'] if(use_service_worker): cmd += ' --service-worker' print('call: ' + cmd) try: subprocess.run(cmd.split()) except KeyboardInterrupt: pass
def remove_item(msg, emp_id, branch_id): logging.debug('Removing an item') c_item = 11 * ' ' + 'CHOOSE ITEM' press = 11 * ' ' + 'PRESS' done = 12 * ' ' + 'DONE' delete = 11 * ' ' + 'DELETE?' where_cond = "branch = {}".format(branch_id) items = sjtrophy.select_table_where('item', where_cond)[0] item_types = [] fmt_items = [] dict = {} for item in items: item_types.append((item[0], item[1])) for item in item_types: fmt_items.append(12 * ' ' + '{} {}'.format(item[0], item[1].upper())) for index, item in enumerate(fmt_items): dict[item] = item_types[index] questions = [inquirer.List('types', message=c_item, choices=fmt_items)] choice = inquirer.prompt(questions)['types'] where_cond = "i_id = {} and i_type = \"{}\"".format( dict[choice][0], dict[choice][1]) result = sjtrophy.select_table_where('item', where_cond) sjtrophy.display_results(result[0][0], result[1]) questions = [inquirer.Confirm('delete', message=delete)] del_yes = inquirer.prompt(questions)['delete'] if del_yes: sjtrophy.delete_rows('item', where_cond) questions = [inquirer.List('done', message=press, choices=[done])] answer = inquirer.prompt(questions)['done'] if answer == done: return
def deleteHost(self, hostList): host = inquirer.prompt([ inquirer.List( 'host', message=constants.SELECT_HOST_TO_DELETE_TEXT, choices=hostList, ), ])['host'] delete = inquirer.prompt([ inquirer.Confirm( 'confirmation', message='Delete ' + host, default=False, ), ])['confirmation'] if (delete): os.remove(constants.INVENTORIES_DIR + '/' + host + constants.INVENTORY_EXTENSION) os.remove(constants.PLAYBOOKS_DIR + '/' + host + constants.PLAYBOOK_FILE_EXTENSION) print print constants.HOST_DELETED_TEXT print else: print print constants.CANCELED_BY_USER_TEXT print
def ask_basics(self): questions = [ inquirer.Text( 'name', message = 'Name of job' ), inquirer.Text( 'description', message = 'Description of job', ), inquirer.Text( 'cronexp', message = 'Cron expression', validate = check_cron, ), inquirer.Confirm( 'enabled', message = 'Enable the job?', default = True, ) ] job = inquirer.prompt(questions) return job
def create_issues(github_selected_repos: List[str]) -> i.Issue: """Prompt questions to create issues.""" questions = [ inquirer.Text( "title", message="Write an issue title", validate=val.not_empty_validation, ), inquirer.Text("body", message="Write an issue body [optional]"), inquirer.Text( "labels", message="Write issue labels [optional, separated by comma]" ), inquirer.Confirm( "correct", message=( "Confirm creation of issue for the project(s) " f"{github_selected_repos}. Continue?" ), default=False, ), ] correct = False while not correct: answers = inquirer.prompt(questions) correct = answers["correct"] labels = ( set(label.strip() for label in answers["labels"].split(",")) if answers["labels"] else set() ) return i.Issue(answers["title"], answers["body"], labels)
def getLoginInfo(region): ''' Getting the username and password ''' try: loginList = [ inquirer.Text( 'username', message="{}Type in your username (email address){}".format( config.BOLD, config.END), validate=lambda _, x: re.match('[^@]+@[^@]+\.[^@]+', x)), inquirer.Password('password', message="{}Type in your password{}".format( config.BOLD, config.END)), inquirer.Password( '2fa', message= "{}Type in your 2FA token (Leave blank if you do not use 2FA){}" .format(config.BOLD, config.END)), inquirer.Confirm( 'store', message= '{}Do you want to store the authentication token on the local drive?{}' .format(config.BOLD, config.END), default=True) ] loginInfo = inquirer.prompt(loginList) loginInfo['region'] = region return loginInfo except TypeError: exitProgram()
def ios(): # Check if it has fastlane setup if not os.path.exists("fastlane/Fastfile"): sys.exit("Fastlane not installed") exec("git status") print( "-------------------------------------------------------------------") # Ask for change log changeLog = input("Change Log: ") questions = [ inquirer.List( 'releaseType', message="What type of release is this?", choices=[('Release', 'release'), ('Beta', 'beta')], ), inquirer.Confirm('screenshots', message="Do you want to generate screenshots?", default=False), ] answers = inquirer.prompt(questions) # Update fastlane exec("bundle update fastlane") if answers['screenshots']: exec("bundle exec fastlane snapshot update --force") exec("bundle exec fastlane snapshot") # Remove old build artifacts exec("rm -f *.dSYM.zip") exec("rm -f *.ipa") # Save the changelog as the release notes exec("echo '" + changeLog + "' > fastlane/metadata/en-US/release_notes.txt") # Update the acknowledgements file (if Settings.bundle exists) if answers['releaseType'] == 'release' and os.path.isdir( "Settings.bundle"): copyfile( "Pods/Target Support Files/Pods-" + projectCode + "/Pods-" + projectCode + "-acknowledgements.plist", "Settings.bundle/Acknowledgements.plist") # Run the correct lane exec("bundle exec fastlane " + answers['releaseType']) # Get the version and build numbers buildNum = os.popen("agvtool what-version -terse").read() buildVers = os.popen( "xcodebuild -showBuildSettings 2> /dev/null | grep MARKETING_VERSION | tr -d 'MARKETING_VERSION =' " ).read() exec("git add .") exec("git commit -am '" + buildNum + ": " + changeLog + "'") exec("git tag " + buildVers) exec("git push")
def select(self): filenames = self.getFilenames() if filenames: while (True): filename = inquirer.prompt([ inquirer.List( 'files', message=self.message, choices=self.getFilenames(), ), ])['files'] correct = inquirer.prompt([ inquirer.Confirm( 'confirmation', message=constants.CONFIRM_FILE_SELECTION_TEXT + " '" + filename + "'", default=True, ), ])['confirmation'] if (correct): return filename else: print else: return None
def download_request(path, link): response = requests.get(link, stream=True) total_length = response.headers.get('content-length') log('start to download (size: %s bytes)' % total_length, LogLevel.INFO) questions = [ inquirer.Confirm('install', message='continue to install dataset on your disk?', default=True) ] answers = inquirer.prompt(questions) if not answers['install']: log('install process is canceled', LogLevel.ERROR) return -1 with tqdm(total=100) as pbar: with open(path, 'wb') as f: if total_length is None: f.write(response.content) else: total_length = int(total_length) for data in response.iter_content(chunk_size=4096): f.write(data) pbar.update(len(data) / total_length * 100) log('download is completed', LogLevel.SUCCESS)
def action_build_docker_image(): print(build_docker_image) # DOCKER_BUILDKIT=1 #os.environ['DOCKER_BUILDKIT'] = "1" # visible in this process + all children questions = [ inquirer.Text('name', message='Welchen Namen soll der Build erhalten?', default='t08094a/ionic'), inquirer.Text('version', message='Welche Version soll der Build erhalten?', default='1.0.0'), inquirer.Confirm('latest', message='Soll mit \'latest\' geflagt werden?', default=True), inquirer.Confirm('with_cache', message='Soll mit Dockers Cache gebaut werden?', default=True) ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) name = answers['name'] version = answers['version'] latest = answers['latest'] with_cache = answers['with_cache'] # save the image name in an invisible file write_content_to_local_settings('Docker', 'image_name', name) cmd = [ 'docker', 'build', '--build-arg', 'USER_ID=$(id -u ${USER})', '--build-arg', 'GROUP_ID=$(id -g ${USER})', '-t', name + ':' + version ] if (latest): cmd.extend(['-t', name + ':latest']) if (not with_cache): cmd.extend(['--no-cache']) cmd.extend(['.']) # z.B. docker build -t t08094a/ionic:1.0.0 -t t08094a/ionic:latest . print(Fore.CYAN + 'call: ' + ' '.join(cmd) + '\n') completed = subprocess.run(cmd)
def ask_gpus_bool(): """ Returns a bool answering whether to use gpu or not """ questions = [ inquirer.Confirm("gpus", message="Should GPUs be used?", default=False) ] return inquirer.prompt(questions)
def check_confirmation(prompt: str, default: bool = False) -> bool: """ Check confirmation of something """ return inquirer.prompt( [inquirer.Confirm("check", message=prompt, default=default)], theme=GreenPassion(), )["check"]
def continue_run(): questionConfirm = [ inquirer.Confirm("continue", message="Should I continue?", default=False), ] answerConfirm = inquirer.prompt(questionConfirm) return answerConfirm["continue"]
def merge_pull_requests( github_username: str, github_selected_repos: List[str] ) -> prm.PullRequestMerge: """Prompt questions to merge pull requests.""" questions = [ inquirer.Text( "base", message="Write base branch name (destination)", default="master", validate=val.not_empty_validation, ), inquirer.Text( "head", message="Write the head branch name (source)", validate=val.not_empty_validation, ), inquirer.Text( "prefix", message="Write base user or organization name from PR head", default=github_username, validate=val.not_empty_validation, ), inquirer.Confirm( "delete_branch", message="Do you want to delete head branch on merge?", default=False, ), inquirer.Confirm( "correct", message=( "Confirm merging of pull request(s) for the project(s) " f"{github_selected_repos}. Continue?" ), default=False, ), ] correct = False while not correct: answers = inquirer.prompt(questions) correct = answers["correct"] return prm.PullRequestMerge( answers["base"], answers["head"], answers["prefix"], answers["delete_branch"], )
def new_order(msg, emp_id, branch_id): logging.info('Creating new order') display_header(msg, 'NEW ORDER', 40) new_cust = 11 * ' ' + "NEW CUSTOMER?" questions = [ inquirer.Confirm('new_customer', message=new_cust, default=True) ] answers = inquirer.prompt(questions) # insert to database return eid (highest eid) if answers['new_customer']: new_customer(msg) # cid = new_customer() else: c = sjtrophy.search_customer() if None == c: cid = new_customer() itm_id = 11 * ' ' + "ENTER ITEM ID" dsg_id = 11 * ' ' + "ENTER DESIGN ID" no_itms = 11 * ' ' + "ENTER NUMBER OF ITEMS FOR ENGRAVING" cust_dsg = 11 * ' ' + "CUSTOM DESIGN?" msg = 'ORDER COMPLETE' questions = [ inquirer.Text('item_id', message=itm_id), inquirer.Confirm('custom_d', message=cust_dsg, default=False) ] answers = inquirer.prompt(questions) iid = answers['item_id'] if answers['custom_d']: did = new_design() else: questions = [inquirer.Text('design_id', message=dsg_id)] answers = inquirer.prompt(questions) did = answers['design_id'] question = [inquirer.Text('count', message=no_itms)] answers = inquirer.prompt(questions) count = answers['count'] # get prices of item and design to derive total cost # insert into customer_order set count, status item, design, customer, last_ud_by, total_cost if sjtrophy.is_manager(emp_id): manager_main_menu(msg, emp_id, branch_id) else: associate_main_menu(msg, emp_id, branch_id)
def shouldDeleteFile(): deleteFile = [ inquirer.Confirm('deleteFile', message="{}Want to delete authtoken file?{}".format( config.BOLD, config.END), default=True) ] if inquirer.prompt(deleteFile)['deleteFile']: os.remove(config.authTokenFile)
def confirm(msg, default='yes'): import inquirer confirm = { inquirer.Confirm('confirmed', message=msg, default=True if default is 'yes' else False), } confirmation = inquirer.prompt(confirm) return confirmation["confirmed"]
def confirm(message: str, default: bool = True): """ A yes/no confirmation. Accepts Message string and True / False for default answer. If no default is provided, True is assigned. """ questions = [ inquirer.Confirm(message, message=message, default=default), ] answers = inquirer.prompt(questions) return answers[message]
def continue_proccess(self): questions = [ inquirer.Confirm('continue', message="Do you wish to continue?"), ] answers = inquirer.prompt(questions) if answers['continue'] == True: return 1 elif answers['continue'] == False: return 0
def open_by_output_args( output_str: str, outputFormat_hint: typing.Optional[OutputFormat], overwrite: typing.Optional[bool], ) -> typing.Iterator[typing.Tuple[typing.BinaryIO, OutputFormat]]: if output_str == '-': if outputFormat_hint is not None: yield sys.stdout.buffer, outputFormat_hint else: # outputFormat_hint is None # default outputFormat is module yield sys.stdout.buffer, OutputFormat.module else: output = Path(output_str).resolve() outputFormat: OutputFormat if outputFormat_hint is not None: outputFormat = outputFormat_hint if outputFormat is OutputFormat.module and output.suffix != ".py": raise ValueError( "--outputFormat=module, but output file suffix is not .py" f", got {output_str!r}") if outputFormat is OutputFormat.xml and output.suffix != ".xml": raise ValueError( "--outputFormat=xml, but output file suffix is not .xml" f", got {output_str!r}") else: # outputFormat_hint is None: if output.suffix == ".py": outputFormat = OutputFormat.module elif output.suffix == ".xml": outputFormat = OutputFormat.xml else: raise ValueError("output file suffix must be .py or .xml" f", got {output_str!r}") try: with output.open("xb") as outputFile: yield outputFile, outputFormat except FileExistsError: if overwrite is None: answer = inquirer.prompt([ inquirer.Confirm( "overwrite", message=(f"Do you want to overwrite {output_str!r}?"), ) ]) if answer: overwrite = answer["overwrite"] else: overwrite = False if not overwrite: raise else: with output.open("wb") as outputFile: yield outputFile, outputFormat
def set_connection(self, registered_tasks, parameters, base_task): question_pipe = [ inquirer.Confirm('onPipe', message = f'[{base_task}] Do you want to pipe another task?', default = False, ) ] question_success = [ inquirer.Confirm('onSuccess', message = f'[{base_task}] Do you want to execute another task on success?', default = False, ) ] question_fail = [ inquirer.Confirm('onFail', message = f'[{base_task}] Do you want to execute another task on fail?', default = False, ) ] ans = inquirer.prompt(question_pipe) if ans['onPipe']: parameters, next_task = self.set_task(registered_tasks, parameters) parameters['tasklist'][base_task]['onPipe'] = next_task parameters = self.set_connection(registered_tasks, parameters, next_task) ans = inquirer.prompt(question_success) if ans['onSuccess']: parameters, next_task = self.set_task(registered_tasks, parameters) parameters['tasklist'][base_task]['onSuccess'] = next_task parameters = self.set_connection(registered_tasks, parameters, next_task) ans = inquirer.prompt(question_fail) if ans['onFail']: parameters, next_task = self.set_task(registered_tasks, parameters) parameters['tasklist'][base_task]['onFail'] = next_task parameters = self.set_connection(registered_tasks, parameters, next_task) return parameters
def new_repos(github_selected_repos: List[str]) -> Any: """Prompt question to know if you want to select new repositories.""" message = "\nThe configured repos will be used:\n" for repo in github_selected_repos: message += f" * {repo}\n" print(message) answer = inquirer.prompt( [inquirer.Confirm("", message="Do you want to select new repositories?")] )[""] return answer
def update_packages_question(self): """ Return question for updating packages """ question = inquirer.Confirm( "update_packages", message="Do you want to update all packages?", default=True, ) return question
def confirmation(self): """ Return confirmation question """ question = inquirer.Confirm( "continue", message="Do you really want to perform the chosen tasks?", default=True, ) return question
def run(self): """ Start the application. Actions ------- 1) Ask questions to the user. 2) Set parameters of the current session. 3) Partition the disk (optional). 4) Mount the partitions. 5) Install Arch Linux. """ app_banner(self) # Ask questions to the user self.user = inquirer.prompt( question_manager(self), theme=load_theme_from_dict(self.theme)) if self.user['confirm'] is False: del self os.execl(sys.executable, sys.executable, * sys.argv) # Set parameters of the current session session_parameters(self) # DEBUG: uncomment those lines for running tests from pprint import pprint pprint(self.user) sys.exit(0) # Partition the disk (optional) run_partitioner(self) # Mount the partitions mount_partitions(self) # Install Arch Linux run_installer(self) # Copy logs to system logging.info(self.trad('installation successful')) dump_json_file('{x}.json'.format(x=self.user['username']), self.user) copytree('logs', '/mnt/var/log/PyArchboot', copy_function=copy2) # Reboot the system msg = self.trad('Do you wish to reboot your computer now') question = [inquirer.Confirm('reboot', message=msg, default=True)] confirm = inquirer.prompt(question, theme=load_theme_from_dict(self.theme)) if confirm['reboot'] is True: app_reboot() else: sys.exit(0)
def Linux_Manual_Continue(): confirm = { inquirer.Confirm('confirmed', message="Do you want to continue?", default=True), } confirmation = inquirer.prompt(confirm) if confirmation["confirmed"]: return 1 else: return 0