def update_existing_channels(channels_file_path: str | Path): with open(channels_file_path, "r+") as file: channels = load(file) changed_channels = [] for channel in channels: if not Confirm.ask( f"Do you want to remove the channel '{channel['name']}'?", default=False, ): if search_keywords := Prompt.ask( f"Do you want to change the search keywords of the channel '{channel['name']}'? \n" f"If so, enter the search keywords that will replace the old ones. If not, just press enter", default=False, ): channel["search_keywords"] = search_keywords.split() changed_channels.append(channel) while Confirm.ask("Do you want to add a new channel?", default=False): name = Prompt.ask("Enter the name of the Telegram channel") search_keywords = Prompt.ask( f"Enter your search keywords for the channel '{name}'. Press Enter if you wish to receive a notification for each message" ).split() changed_channels.append( asdict(SubscribedChannel(name, search_keywords))) file.seek(0) dump(changed_channels, file) file.truncate()
async def setup_config(config_exists: bool): if config_exists: if Confirm.ask( "Telegram API config already exist, do you want to create a new one?", default=False, ): Config.create(config_path) if Confirm.ask( f"\nYour channels: \n" f"{SubscribedChannel.show_from_json(channels_file_path)} \n" f"Do you want to modify these channels?", default=False, ): SubscribedChannel.update_existing_channels(channels_file_path) if Confirm.ask( "Telegram session already exist, do you want to create a new one? Type y if you want to update your subscribed channels.", default=False, ): config = Config.from_path(config_path) await setup_telegram_session(config) else: Config.create(config_path) SubscribedChannel.create_config_file(channels_file_path) config = Config.from_path(config_path) await setup_telegram_session(config)
def generate_password(self): """Generate a new password based on user requirements""" has_symbols = Confirm.ask("Do you want it to have symbols?") has_letters = True # Always have letters has_numbers = Confirm.ask("Do you want it to have numbers?") while True: length = IntPrompt.ask( "Enter a number between [b]8[/b] and [b]128[/b]", default=32) if 8 <= length <= 128: break password = self.pass_obj.generate_password(has_symbols, has_letters, has_numbers, length) self.print(password, style="yellow on black") self.print('Password was generated and copied to clipboard!', style="green on white")
def ask_confirmation(action, kind): if action == Action.delete: confirmation = Confirm.ask( f"Are you sure you want to delete the listed {kind}?", default=False) elif action == Action.not_monitored: confirmation = Confirm.ask( f"Are you sure you want to change the listed {kind} to not-monitored?", default=False) elif action == "re-add": confirmation = Confirm.ask( f"Are you sure you want to re monitor the listed {kind}?", default=False) return confirmation
def eula_true(server_name): """Points to the eula.txt generated from the server executable, generates text to auto-accept the eula """ eula_dir = os.path.join(serverDir[server_name], 'eula.txt') # with acts like a try/finally block in this case with open(eula_dir, 'r') as file: # read a list of lines into data data = file.readlines() # now change the last line (containing the eula acceptance). if data[-1] != 'eula=true': accept_eula = Confirm.ask( "[bold yellow]Would you like to accept the Mojang EULA?[/bold yellow]", default=True) if accept_eula is True: data[-1] = 'eula=true' console.print('\nEULA Accepted and server is ready to go!!', style='bold green') else: console.print( "EULA not accepted. You can do this later within the 'eula.txt' file", style="bold red") # and write everything back with open(eula_dir, 'w') as file: file.writelines(data)
def excepthook( type_, value, traceback, ): # cache error message if not len(value.args): value.args = ["No message"] cache_error(f"{type_.__name__}: {value.args[0]}", value.__doc__) # show error traceback emanager = ErrorManager( type_, value, traceback, keep_frames, all_locals, relevant_only, hide_locals, ) if isinstance(value, AttributeError): emanager.render_attribute_error() else: emanager.render_error() # Ask user if they want to google the error if enable_prompt: if Confirm( ).ask("\n[white]Do you want me to google solutions to this error? " ): get_answers(hide_panel=True)
def sample_check( fastqs, pipeline, output, quality, ratio, distance, filter, offset, ): samples = {f.name.split(".")[0]: f for f in fastqs} queue_all = not pipeline.is_dir() processed_samples = make_sample_check_table( sorted(samples.keys()), pipeline, output, quality, ratio, distance, filter, offset, queue_all, ) if len(processed_samples) != len(samples) and not Confirm.ask( "Continue with these samples?"): sys.exit() return [f for sample, f in samples.items() if sample in processed_samples]
def single_cell( input, pipeline, output, error, minimum_length, length, upstream_adapter, downstream_adapter, threads, verbose, ): for d in [pipeline, output]: d.mkdir(exist_ok=True) # TODO: raise error if can't get sample name sam_files = {f.name.split(".")[0]: f for f in input.iterdir()} for f in sam_files.values(): ext = f.suffix if ext != ".sam": raise ValueError( "There is a non sam file in the provided input directory:") console.print( f"[b cyan]Samples[/]: {', '.join(sorted(sam_files.keys()))}\n") if not Confirm.ask("Continue with these samples?"): sys.exit() for sample, f in sam_files.items(): print() console.print(f"──────────────── {sample} ───────────────────", style="dim") with console.status( f"Processing sample: [green]{sample}[/green]\r\n", spinner="dots12", ) as status: single_cell_process( sample, f, pipeline, output, error, minimum_length, length, upstream_adapter, downstream_adapter, threads, verbose, status, ) console.print(f"[green]{sample}[/green]: processing completed") console.print("\n[green]FINISHED!") sys.exit()
def main(): # help menu if "-h" in sys.argv: help() exit(code=0) # confirm b4 scraping if "-y" in sys.argv: confirmation = True else: confirmation = Confirm.ask( "[blue underline]Proceed to scrape headlines?[/blue underline]") if confirmation == False: console.print("[red]exiting[/red]") exit(code=0) # import the options options = importSettings(parentDir + '/' + 'settings.json') myDesc = "[yellow]scraping[/yellow]" # scrape headlines from all the websites siteList = track(websites, console=console, description=myDesc, auto_refresh=True) for website in siteList: myDesc = "scraping [yellow]" + website['name'] + "[/yellow]" website["headlines"] = scrape(website) # export headlines to the output file export(options)
def build_script(self) -> str: project = gerbers.GerberProject( os.path.abspath(os.path.expanduser(self.options.directory))) generator = flatcam.FlatcamProjectGenerator( project, config.get_merged_config(self.options.config)) existing_files = self.get_existing_output() if existing_files: self.console.print( "The following existing flatcam output was found: ") for filename in sorted(existing_files): self.console.print(f"- {filename}") delete_existing = Confirm.ask("Would you like to delete these?") if delete_existing: for filename in existing_files: os.unlink( os.path.join( os.path.abspath( os.path.expanduser(self.options.directory)), filename, )) output_file = os.path.join( self.options.directory, "generate_gcode.FlatScript", ) processes = generator.get_cnc_processes() with open(output_file, "w") as outf: for process in processes: outf.write(str(process)) outf.write("\n") return output_file
async def config_command(): config_exists = Path(config_path).exists() if config_exists and not Confirm.ask( "Config already exist, do you want to modify?", default=False): return await setup_config(config_exists)
def prompt_configuration(): config = get_configuration() if not config: config = {"clientid": None, "clientsecret": None, "customerid": None} while True: config["customerid"] = Prompt.ask("CustomerId", default=config["customerid"]) config["clientid"] = Prompt.ask("ClientId", default=config["clientid"]) config["clientsecret"] = Prompt.ask( "ClientSecret", password=True, default=config["clientsecret"], show_default=False, ) goodcredentials = True try: console.print("Validating credentials... ", end=None) authenticate_api(config, use_cache=False) console.print("Success.", style="green") except AuthenticationException: console.print("Error. Please check the credentials.", style="red") goodcredentials = False if goodcredentials and Confirm.ask( "Please confirm to store this configuration in the OS keying" ): keyring.set_password("cxcli", ":customerid", config["customerid"]) keyring.set_password("cxcli", ":clientid", config["clientid"]) keyring.set_password("cxcli", ":clientsecret", config["clientsecret"]) # invalidate access_token keyring.set_password("cxcli", ":access_token_timestamp", "0") console.print("Configuration stored successfully.", style="GREEN") break
def process(self, plugin_name: str, version: Optional[str] = None): if plugin_name.endswith(".git"): success = self._install_plugin_by_git(plugin_name, version) else: plugin_info = self._find_plugin_from_registry(plugin_name) if plugin_info is None: click.secho( "Plugin {} is not registered in the registry".format( plugin_name), fg="red") return print(plugin_info.repository) current_version = self._find_plugin_from_installed_plugins( plugin_name) if current_version is None: success = self._install_plugin_by_git(plugin_info.repository, plugin_info.branch) else: console = Console() console.print( "\n{} is already installed ( Installed version: {} ).". format(plugin_name, current_version)) if not Confirm.ask('Do you want to update to new version?'): return success = self._update_plugin_by_git(plugin_info.repository, plugin_info.branch) if not success: click.secho("Failed to install plugin {}".format(plugin_name), fg="red")
def add_schema_found_configs(self): """ Add anything that's found in the Nextflow params that's missing in the pipeline schema """ params_added = [] params_ignore = self.pipeline_params.get("schema_ignore_params", "").strip("\"'").split(",") params_ignore.append("schema_ignore_params") for p_key, p_val in self.pipeline_params.items(): # Check if key is in schema parameters if p_key not in self.schema_params and p_key not in params_ignore: if ( self.no_prompts or self.schema_from_scratch or Confirm.ask( ":sparkles: Found [bold]'params.{}'[/] in the pipeline config, but not in the schema. [blue]Add to pipeline schema?".format( p_key ) ) ): if "properties" not in self.schema: self.schema["properties"] = {} self.schema["properties"][p_key] = self.build_schema_param(p_val) log.debug("Adding '{}' to pipeline schema".format(p_key)) params_added.append(p_key) return params_added
def ensureNoMissingFiles(aCurrentProj, aDepFileParser): """ Check the dependency file tree for unresolved files. If detected, ask the user for confirmation to continue """ from ..depparser import DepFormatter if not aDepFileParser.unresolved: return fmt = DepFormatter(aDepFileParser) cprint( "ERROR: Project '{}' contains unresolved dependencies: {} unresolved file{}." .format( aCurrentProj, len(aDepFileParser.unresolved), ("" if len(aDepFileParser.unresolved) == 1 else "s"), ), style='red') cprint(fmt.draw_unresolved_files(), style='red') cprint("") if not Confirm.ask("Do you want to continue anyway?"): raise Abort()
def check_weights_config( config: 'bittensor.Config'): if config.subtensor.network == bittensor.defaults.subtensor.network and not config.no_prompt: config.subtensor.network = Prompt.ask("Enter subtensor network", choices=bittensor.__networks__, default = bittensor.defaults.subtensor.network) if config.wallet.name == bittensor.defaults.wallet.name and not config.no_prompt: if not Confirm.ask("Show all weights?"): wallet_name = Prompt.ask("Enter wallet name", default = bittensor.defaults.wallet.name) config.wallet.name = str(wallet_name) config.all_weights = False if not Confirm.ask("Show all hotkeys?"): hotkey = Prompt.ask("Enter hotkey name", default = bittensor.defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey) config.all_hotkeys = False else: config.all_hotkeys = True else: config.all_weights = True
def get_profile_from_user(profiles: List[str]) -> str: profile = Prompt.ask(" Enter the name of profile you want to use", choices=profiles) if Confirm.ask(" Save profile as default?"): CONFIG.update_option_value("defaults", "profile", profile) return profile
def check_db(): """检查数据库是否存在""" from rich.prompt import Confirm if not os.path.exists(pypaths.db_path): if Confirm.ask(f'cmder database not found, do you want to download?', default=True): update_database()
def press_enter_to(message: str) -> bool: confirm = Confirm.ask( "[bold]*[/bold] Press Enter to " + message, show_choices=False, show_default=False, choices=[""], ) return confirm
def _is_used(my_file: str) -> None: """ Checks if the user is already kept opened the excel file trying to write """ while True: try: with open(my_file, "a+"): break except IOError: if Confirm.ask("File Closed ?", default="(y)", show_default=True): pass
def launch_workflow(self): """ Launch nextflow if required """ log.info( "[bold underline]Nextflow command:[/]\n[magenta]{}\n\n".format( self.nextflow_cmd)) if Confirm.ask("Do you want to run this command now? "): log.info("Launching workflow! :rocket:") subprocess.call(self.nextflow_cmd, shell=True)
def __init__(self, folder_name = None): os.system("cls") self.console = Console() self.folder_name = folder_name if self.folder_name != None: os.system("mkdir {}".format(folder_name)) os.chdir(os.getcwd() + f"\\{folder_name}") # check for update if __import__('discli').__version__ != Variables.VERSION: self.console.print(f"New version is released please install via [red]pip install --upgrade discli [/red], {Variables.VERSION}: {Variables.RELEASENOTE}") sys.exit() self.console.print(Variables.BANNER) self.console.print(f"\nDiscord Bot CLI v{Variables.VERSION} for creating projects") self.console.print("Copyright (c) 2020, [link=https://github.com/zenqii][magenta]Zenqi[/magenta][/link]. All rights reserved.") user_name = getpass.getuser() +"bot" config = {} bot_token = "" bot_name = Prompt.ask("\n[green]»[yellow] Enter your desire bot name", default=user_name) while bot_token == "": bot_token = Prompt.ask("[green]»[yellow] Enter your bot token [red](required)") prefix = Prompt.ask("[green]»[yellow] Enter bot prefix", default="!") is_heroku = Confirm.ask("\n[green]»[magenta] Would you like to add heroku support?") config["name"] = bot_name config["token"] = bot_token config["prefix"] = prefix config["heroku"] = is_heroku for _ in track(range(50), description="[green]»[cyan] Initializing discli.."): time.sleep(.1) work = True with self.console.status("[green]»[bold magenta] Creating ext folder...",) as status: while work: self.console.log("[green]»[cyan] Config file created: [blue]{}".format(config)) self.create_config(os.getcwd(), config, is_heroku) self.create_main_file(os.getcwd()) self.copy_extension(os.getcwd()) work = False time.sleep(1) break
def delete( graph_id: str = Option(""), force: bool = Option(False, "-f", "--force", help=_force_help), graph: Path = Argument(None, exists=True, help=_graph_help), ): """Delete a graph from the Patterns studio. This will not delete any files locally. """ ids = IdLookup( explicit_graph_path=graph, explicit_graph_id=graph_id, ) with abort_on_error("Deleting graph failed"): if not force: Confirm.ask(f"Delete graph {ids.graph_name}?") delete_graph(ids.graph_id) sprint(f"[success]Graph deleted from Patterns studio.")
def purgetasks(ctx, yes): """删除所有离线下载任务""" api = _recent_api(ctx) if not api: return if not yes: if not Confirm.ask("确定删除[i red]所有的[/i red]离线下载任务?", default=False): return _cloud.purge_all_tasks(api)
def test_prompt_confirm_default(): INPUT = "foo\nNO\ny" console = Console(file=io.StringIO()) answer = Confirm.ask("continue", console=console, stream=io.StringIO(INPUT), default=True) assert answer is True expected = "continue [y/n] (y): Please enter Y or N\ncontinue [y/n] (y): Please enter Y or N\ncontinue [y/n] (y): " output = console.file.getvalue() print(repr(output)) assert output == expected
def create_config_file(cls, channels_file_path: str | Path): channels = [] while Confirm.ask("Do you want to add a channel?", default=True): name = Prompt.ask("Enter the name of the Telegram channel") search_keywords = Prompt.ask( f"Enter your search keywords for the channel '{name}'. Press Enter if you wish to receive a notification for each message" ).split() channels.append(SubscribedChannel(name, search_keywords)) with open(channels_file_path, "w") as channels_file: channels = [asdict(channel) for channel in channels] dump(channels, channels_file)
def prompt_gnome_shell_themes(): add_shell_theme = Confirm.ask( "Do you want to enter gnome shell theme too? [yes/no]") if add_shell_theme: day_theme_msg = 'Pick Gnome shell theme chosen during the day' night_theme_msg = 'Pick Gnome shell theme chosen during the night' themes_list = gnome_shell_themes() day_shell_theme = pick(themes_list, day_theme_msg) themes_list.remove(day_shell_theme) night_shell_theme = pick(themes_list, night_theme_msg) return str(day_shell_theme), str(night_shell_theme) return None
def _check_sleep(self): """ If running on interval, handle analyzing and sleep interval """ if self.login_attempts == self.attempts: if self.analyze: analyzer = Analyzer(self.output, self.notify, self.webhook, self.host, self.total_hits) new_hit_total = analyzer.analyze() # Pausing if specified by user before continuing with spray if new_hit_total > self.total_hits and self.pause: print() console.print( f"[+] Successful login potentially identified. Pausing...", style="good", ) print() Confirm.ask( "[blue]Press enter to continue", default=True, show_choices=False, show_default=False, ) print() else: new_hit_total = ( 0 # just set to zero since results aren't being analyzed mid-spray ) print() console.print( f'[yellow][*] Sleeping until {(datetime.datetime.now() + datetime.timedelta(minutes=self.interval)).strftime("%m-%d %H:%M:%S")}[/yellow]' ) time.sleep(self.interval * 60) print() # reset counter and set hit total self.login_attempts = 0 self.total_hits = new_hit_total
def reset(): """ Reset the configuration to default. """ if Confirm.ask("\n:bomb: Are you sure you want to reset the config file?"): reset_config() console.print( Panel.fit( f":thumbs_up_dark_skin_tone: Successfully reset the config file: {config_path} :thumbs_up_dark_skin_tone:" ), style="bold green", )
def ask_unite_button(): if not UNITE_PATH.exists(): print('Warning: Unite extension not found at path', str(UNITE_PATH)) return False, None ans = Confirm.ask( 'Do you want to switch day night unite buttons? [yes/no]') if ans: pick_ans = Confirm.ask( 'Do you want to choose button theme? [default is united-dark/united-light]' ) if pick_ans: theme_list = [x.basename for x in (UNITE_PATH / 'themes').dirs()] day_theme = pick(theme_list, 'Select day button theme:') print() theme_list.remove(day_theme) night_theme = pick(theme_list, 'Select night button theme:') else: day_theme = 'united-dark' night_theme = 'united-light' return ans, (day_theme, night_theme) else: return ans, None