def start_commands(gradebook): command = '' print('Welcome!') print('Enter "course" to select a course to view') command = Prompt.ask("Enter a command") while command.lower() != 'end': if command == 'course': grid = Table() grid.add_column('ID') grid.add_column('Course') count = 1 for course in gradebook.courses: grid.add_row(str(count), course.title) count += 1 console.print(Columns( (grid, ), align="center", expand=True, ), ) course_id = IntPrompt.ask( "Enter the ID of the course you want to view") console.clear() gradebook.courses[course_id - 1].print_grade_table() course_commands(gradebook.courses[course_id - 1]) console.clear() print_grade_table(gradebook) elif command == 'help': print('[green bold] course: Pick a course to view') print('[red bold] end: Exit Scholaris') else: console.clear() print_grade_table(gradebook) print( "[red]Invalid command! Enter 'help' to see possible commands") command = Prompt.ask("Enter a command")
def check_overview_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: wallet_name = Prompt.ask("Enter wallet name", default = bittensor.defaults.wallet.name) config.wallet.name = str(wallet_name)
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()
def sh( name: str = typer.Argument(..., help="Approximate container name"), shell_path: str = typer.Argument("/bin/sh", help="shell path inside the container"), ): """ Jump into container shellssss """ console = Console() client = docker.from_env() containers = client.containers.list() found_containers = [] for container in containers: if name in container.attrs["Name"]: found_containers.append(container) if len(found_containers) == 0: print("[bold red]Container not found[/bold red]") print("Running containers :") _print_containers_table(console, containers) input_name = Prompt.ask("Please specify which one you want :") sh(input_name, shell_path) return elif len(found_containers) > 1: print(f"[bold dark_orange]Multiple containers with similar name ({name}) : [/bold dark_orange]") _print_containers_table(console, found_containers) input_name = Prompt.ask("Please specify which one you want :", default=found_containers[0].attrs["Name"]) sh(input_name, shell_path) return container: Container = found_containers[0] p = subprocess.Popen(["docker", "exec", "-it", container.attrs["Config"]["Hostname"], str(shell_path)]) p.communicate()
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 fetch_data(full_url: str) -> dict: """ Sends request to API and recieves weather data, converts it from JSON to dict. Parameters: full_url (str): API call URL. Returns: data_dict (dict): Data dictionary. """ try: with urllib.request.urlopen(full_url) as url: data = url.read().decode('utf-8') data_dict = json.loads(data) return data_dict except urllib.error.HTTPError as e: if e.code == 404: save = Prompt.ask( "[bold red]Please check the city name, use [/bold red][bold blue]https://openweathermap.org/find[/bold blue][bold red] to find city names.[bold red] Edit config now?[/bold red]", choices=["Y", "N"]) save_config() if save == 'Y' else print( "[bold red]Exiting...[/bold red]") exit(1) elif e.code == 401: save = Prompt.ask( "[bold red]Please check your API key, you can get it from [/bold red][bold blue]https://openweathermap.org/api[/bold blue].[bold red] Edit config now?[/bold red]", choices=["Y", "N"]) save_config() if save == 'Y' else print( "[bold red]Exiting...[/bold red]") exit(1) else: print("[bold red]An error has occurred.\nExiting...[/bold red]") exit(1)
def check_new_hotkey_config( config: 'bittensor.Config' ): if config.wallet.name == bittensor.defaults.wallet.name and not config.no_prompt: wallet_name = Prompt.ask("Enter wallet name", default = bittensor.defaults.wallet.name) config.wallet.name = str(wallet_name) if config.wallet.hotkey == bittensor.defaults.wallet.hotkey and not config.no_prompt: hotkey = Prompt.ask("Enter hotkey name", default = bittensor.defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey)
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 check_register_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: wallet_name = Prompt.ask("Enter wallet name", default = bittensor.defaults.wallet.name) config.wallet.name = str(wallet_name) if config.wallet.hotkey == bittensor.defaults.wallet.hotkey and not config.no_prompt: hotkey = Prompt.ask("Enter hotkey name", default = bittensor.defaults.wallet.hotkey) config.wallet.hotkey = str(hotkey)
def create(cls, config_file_path: str | Path) -> Config: api_id = Prompt.ask("Enter your Telegram API id") api_hash = Prompt.ask("Enter your Telegram API hash") config = Config(api_id, api_hash) with open(config_file_path, "w") as config_file: for field in config.__dataclass_fields__: value = getattr(config, field) config_file.write(f"{field}={value}") config_file.write("\n") return config
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 getStudentVueData(): username = IntPrompt.ask('Enter your user id') pwd = Prompt.ask('Enter your password') domain = 'https://md-mcps-psv.edupoint.com' remember = Confirm.ask('Do you want to be remembered?') studentvue_client = StudentVue(str(username), pwd, domain) while 'RT_ERROR' in studentvue_client.get_gradebook().keys(): text = Text('Username or password is incorrect. Try again') text.stylize(style="red") console.print(text) username = IntPrompt.ask('Enter your user id') pwd = Prompt.ask('Enter your password') studentvue_client = StudentVue(str(username), pwd, domain) return studentvue_client.get_gradebook()
def delete_password(self): """Delete an existing password""" tags = Prompt.ask( "Enter the tag(s) to search for the password (separate with spaces if multiple)", default="all") tags = tags.split(' ') if tags[0] == 'all': tags = None len_passwords, all_passwords = self.db_obj.get_passwords( db_name=self.db_name, search_tags=tags) if len_passwords > 0: ids_list = [password['_id'] for password in all_passwords] self.display_passwords(len_passwords, all_passwords, choosing=False) choices = [str(x) for x in range(1, len(ids_list) + 1)] choices.append('exit') choices.append('all') pass_to_delete = Prompt.ask( "Enter the number of password data to delete.", choices=choices, default='exit') if pass_to_delete == 'all': flagged = False for ids in ids_list: done = self.db_obj.delete_password(db_name=self.db_name, _id=ids) if not done: self.print('Failed to delete a password!', style="red on white") flagged = True break if not flagged: self.print('Done!', style="green on white") elif pass_to_delete == 'exit': return else: pass_to_update = int(pass_to_delete) pass_to_update -= 1 done = self.db_obj.delete_password( db_name=self.db_name, _id=ids_list[pass_to_update]) if not done: self.print('Failed to delete the password!', style="red on white") else: self.print('Done!', style="green on white") else: self.print('Nothing to show!', style="red on white")
def importlang(): console.clear() logo() bilgi("\n\[1] Türkçe\n\[2] Azərbaycanca\n\[3] English\n\[4] O'zbek") Dil = Prompt.ask( "[bold yellow]Bir dil seçin / Please select a language[/]", choices=["1", "2", "3", "4"], default="1") if Dil == "1": COUNTRY = "Turkey" LANGUAGE = "TR" TZ = "Europe/Istanbul" elif Dil == "2": COUNTRY = "Azerbaijan" LANGUAGE = "AZ" TZ = "Asia/Baku" elif Dil == "3": COUNTRY = "United Kingdom" LANGUAGE = "EN" TZ = "Europe/London" elif Dil == "4": COUNTRY = "Uzbekistan" LANGUAGE = "UZ" TZ = "Asia/Tashkent" return COUNTRY, LANGUAGE, TZ
def ask( prompt: str = "", *, console: Optional[Console] = None, password: bool = False, choices: Optional[List[str]] = None, show_default: bool = True, show_choices: bool = True, ) -> str: """wrapper function for rich.Prompt().ask() Handles KeyBoardInterrupt, EoFError, and exits if user inputs "abort" """ if choices: choices += ["abort"] try: choice = Prompt.ask( prompt, console=console, password=password, choices=choices, show_default=show_default, show_choices=show_choices ) except (KeyboardInterrupt, EOFError): abort() if choice.lower() == "abort": abort() return choice
def open_url(argv: list = None): """ 打开命令行参数中的链接 open urls in argv :return: None """ import webbrowser as wb from .NetTools import formatUrl if not argv: argv = sys.argv[2:] if argv: for url in argv: url = formatUrl(url) wb.open_new_tab(url) else: pyperclip = requirePackage('pyperclip') try: url = pyperclip.paste() except: url = qs_default_input.ask( 'Sorry, but your system is not supported by `pyperclip`\nSo you need input content manually: ' if user_lang != 'zh' else '抱歉,但是“pyperclip”不支持你的系统\n,所以你需要手动输入内容:', console=qs_default_console) wb.open_new_tab(formatUrl(url))
def main(): welcome() csvpath = Prompt.ask( "[color(11)]Please enter path to data source[/color(11)]") os.system('cls||clear') outputpath = f"{csvpath.replace('.csv', '')}_output.csv" with open(csvpath, 'r', encoding='utf-8') as csvfile, open( outputpath, 'a', encoding='utf-8') as csvoutfile: existing_data_length = existing_data(outputpath) csvreader = csv.DictReader(csvfile) header_row = csvreader.fieldnames header_row.append('decision') csvwriter = csv.DictWriter(csvoutfile, fieldnames=header_row) if existing_data_length == 0: csvwriter.writeheader() for i, row in enumerate(csvreader, 1): if i > existing_data_length: try: welcome() quest = Panel(question(row, i)) console.print(quest) ans, row = answer(row) csvwriter.writerow(row) except Exception: row['decision'] = 'ERROR' csvwriter.writerow(row) console.print_exception()
def create(): global temp_name, algorithm_name indx = sys.argv.index('-c') try: temp_name = sys.argv[indx + 1] algorithm_name = sys.argv[indx + 2] except IndexError: if temp_name != 'main': with open(config['compile_filename'], 'r') as file: ct = file.read() with open(config['template_root'] + temp_name, 'w') as file: file.write(ct) return else: return QproDefaultConsole.print( QproWarnString, 'usage: tmpm -c <template> [algorithm]' if user_lang != 'zh' else '使用: tmpm -c <模板> [算法]' ) temp_name += '.md' if os.path.exists(config['template_root'] + temp_name): from rich.prompt import Prompt if Prompt.ask(( 'Template {temp_name} is already exist, would you cover it?[y/n]' if user_lang != 'zh' else '模板 {temp_name} 已经存在, 是否覆盖它?[y/n]' ).format(temp_name=temp_name), default='n') == 'n': exit(0) content = match_algorithm() write_algorithm(temp_name, algorithm_name, content, 'w')
def new_habit_freq_start_date(self, date_today: arrow.Arrow) -> None: """Get new frequency and start date. :param date_today: :return: """ console.print( f"[bold]{escape('[perry-bot]:')}[/bold] " f"How frequent is this habit?", style="default", ) console.print( "[b]1.[/b] Daily\n[b]2.[/b] Weekly\n[b]3.[/b] " "Every other week\n[b]4.[/b] Monthly\n" "[b]5.[/b] Every other month\n[b]6.[/b] Yearly", style="default", ) frequency = IntPrompt.ask( choices=["1", "2", "3", "4", "5", "6"], default=1, show_default=True, ) freq_str = self.new_habit_freq_to_string(frequency=frequency) self.frequency.append(freq_str) console.print( f"[bold]{escape('[perry-bot]:')}[/bold] " f"What's the start date (YYYY-MM-DD) of this habit?", style="default", ) start_date_input = Prompt.ask(default=date_today.format("YYYY-MM-DD"), show_default=True) start_date = self.check_date_format(start_date_input=start_date_input, date_today=date_today) self.start_date.append(start_date)
def main(): text = "[white on red]Arg1[/white on red]" text += "[red][图片第一页][/red]" url = Prompt.ask(text) session = requests.Session() response = session.get(f"{url}?page=1") soup = BeautifulSoup(response.text, "html.parser") # title = soup.find("h1", class_="title").get_text() total = soup.find("li", class_="next-page").previous_sibling.string for index in range(1, int(total) + 1): detail_url = f"{url}?page={index}" print(detail_url) if index == 1: soup = soup else: response = session.get(detail_url) soup = BeautifulSoup(response.text, "html.parser") try: image_url = soup.find("div", class_="entry") image_url = image_url.find("p").find("img").get("src") image_name = image_url.split('/')[-1] _name_, _type_ = image_name.split(".") image_name = f"{str(index).zfill(2)}.{_type_}" except: continue download(image_url, image_name) time.sleep(3) session.close()
def remove_unused_cms(self): if len(self.unused_cms) == 0: print("There is no unused CMS") else: choice = Prompt.ask("Do you want to clean up {} unused CMS".format(len(self.unused_cms)), choices=["Y", "N"]) if choice == 'Y': failed_cms = [] t = timer() with MyProgress("[progress.description]{task.description}", BarColumn(), TextColumn(text_format="[progress.percentage]{task.percentage:>3.0f}% [green]{task.completed} of {task.total} [bold green] | Success: [bold white]{task.fields[success]} | [bold red]Faied: [bold white]{task.fields[failed]} "), "Took [bold blue]{task.fields[time_elapsed]}s") as progress: task = progress.add_task(total=len(self.unused_cms), description='Deleting unused CMS', success=0, failed=0, time_elapsed=0) for cms_item in self.unused_cms: delete_cmd = 'rm -rf {}'.format(cms_item.get_dir()) out = subprocess.Popen(delete_cmd,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.communicate() status_code = out.poll() self.success += 1 if status_code == 0 else 0 if status_code != 0: failed_cms.append(cms_item) self.failed += 1 progress.advance(task) progress.update(task, success=self.success, failed=self.failed, time_elapsed=int(timer() - t)) if len(failed_cms) > 0: console.print("[bold red]These CMS are failed to delete:") for cms_item in failed_cms: console.print('[bold purple]' + str(cms_item))
def importlang(): console.clear() logo() basarili( "\n\n[1] Türkçe\n\n[2] Azərbaycanca\n\n[3] English\n\n[4] O'zbek\n") Dil = Prompt.ask( "[bold yellow]💬 Bir dil seçin\n💬 Please select a language\n[/]", choices=["1", "2", "3", "4"], default="1") if Dil == "1": COUNTRY = "Turkey" LANGUAGE = "TR" TZ = "Europe/Istanbul" elif Dil == "2": COUNTRY = "Azerbaijan" LANGUAGE = "AZ" TZ = "Asia/Baku" elif Dil == "3": COUNTRY = "United Kingdom" LANGUAGE = "EN" TZ = "Europe/London" elif Dil == "4": COUNTRY = "Uzbekistan" LANGUAGE = "UZ" TZ = "Asia/Tashkent" return COUNTRY, LANGUAGE, TZ
def view_mood_table(self, view_date: str): """Print a mood table given a date. :param view_date: :return: """ self.query(date=view_date) table = self.make_table(title="Mood Records") if self.id: if len(table.rows) >= 20: console.print( f"[bold]{escape('[perry-bot]:')}[/bold] The table has more " f"than 20 rows. Would you like to continue displaying the table?", style="default", ) q = Prompt.ask(choices=["y", "n"]) if q in ["n"]: console.print( f"[bold]{escape('[perry-bot]:')}[/bold] --view-table cancelled.", style="default", ) return console.print(table, style="default") else: console.print( f"[bold]{escape('[perry-bot]:')}[/bold] Sorry, there are no records " f"matching {view_date}. Try another date.", style="default", )
def revert(): indx = sys.argv.index('-r') try: file_name = sys.argv[indx + 1] except IndexError: from rich.prompt import Prompt ls = os.listdir(config['template_root']) rls = [] cnt = 1 for i in ls: QproDefaultConsole.print('[%d] %s' % (cnt, i), end='\t' if cnt % 8 else '\n') rls.append(i) cnt += 1 if cnt % 8: QproDefaultConsole.print() try: indx = int(Prompt.ask('选择')) if indx < 0 or indx > len(rls): raise IndexError except: return QproDefaultConsole.print(QproErrorString, 'Choose out of index') file_name = rls[indx - 1] return init(file_name) if os.path.exists(config['template_root'] + file_name): init(file_name) else: return QproDefaultConsole.print(QproErrorString, 'No such backup')
def _validate_version(self, version): elem = version.split(".") for e in elem: if not e.isdigit(): raise Exception( "Not a valid version number: {0} (should contain only digits)" .format(version)) if not len(elem) == 3: raise Exception( "Not a valid version number: {0} (should contain three elements)" .format(version)) confirm = Prompt.ask( "Please confirm you want to release version {0} (y/N)".format( version), choices=["Y", "N", "y", "n"], default="N", ) # confirm = "" # while confirm not in ("Y", "N"): # confirm = prompt( # "Please confirm you want to release version {0} (Y/N)".format( # version # ) # ) # confirm = confirm.strip().upper() if confirm.upper() == "Y": return version else: raise Exception("Please re-enter the version number")
def revert(): indx = sys.argv.index('-r') try: file_name = sys.argv[indx + 1] except IndexError: from rich.prompt import Prompt ls = os.listdir(config['template_root']) rls = [] cnt = 1 stdSuffix = config['compile_filename'].strip().split('.')[-1] for i in ls: iSuffix = i.split('.')[-1] if iSuffix != stdSuffix and '.' in i: continue QproDefaultConsole.print('[%d] %s' % (cnt, i), end='\t' if cnt % 8 else '\n') rls.append(i) cnt += 1 if cnt % 8: QproDefaultConsole.print() try: indx = int(Prompt.ask('选择' if user_lang == 'zh' else 'Choose')) if indx < 0 or indx > len(rls): raise IndexError except: return QproDefaultConsole.print(QproErrorString, 'Choose out of index' if user_lang == 'zh' else '选择') file_name = rls[indx - 1] return init(file_name) if os.path.exists(config['template_root'] + file_name): init(file_name) else: return QproDefaultConsole.print(QproErrorString, 'No such backup' if user_lang != 'zh' else '没有这个备份')
def get_token() -> str: """Get token via input. Returns ------- str The token choose by user. """ token = "" while not token: token = Prompt.ask( "Please enter the bot token " "(you can find it at https://discord.com/developers/applications)", console=console, ) if ( re.fullmatch( r"([a-zA-Z0-9]{24}\.[a-zA-Z0-9_]{6}\.[a-zA-Z0-9_\-]{27}" r"|mfa\.[a-zA-Z0-9_\-]{84})", token, ) is None ): console.print("[prompt.invalid]ERROR: Invalid token provided") token = "" return token
def access_shared( self, shared_url: str, password: str, vcode_str: str = "", vcode: str = "", show_vcode: bool = True, ): while True: try: self._baidupcs.access_shared(shared_url, password, vcode_str, vcode) return except BaiduPCSError as err: if err.error_code not in (-9, -62): raise err if show_vcode: if err.error_code == -62: # -62: '可能需要输入验证码' print("[yellow]Need vcode![/yellow]") if err.error_code == -9: print("[red]vcode is incorrect![/red]") vcode_str, vcode_img_url = self.getcaptcha(shared_url) img_cn = self.get_vcode_img(vcode_img_url, shared_url) img_buf = BytesIO(img_cn) img_buf.seek(0, 0) img = Image.open(img_buf) img.show() vcode = Prompt.ask("input vcode") else: raise err
def get_ip() -> str: """Get ip via input. Returns ------- str The ip choose by user. """ ip = "" # pylint: disable=line-too-long ipv4_pattern = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" ipv6_pattern = r"^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))" while not ip: ip = Prompt.ask( "Please the ip of this machine " "(you can find it with `curl ifconfig.me`)", console=console, ) ipv4 = re.match(ipv4_pattern, ip) ipv6 = re.match(ipv6_pattern, ip) if not ipv4 and not ipv6: console.print("[prompt.invalid]ERROR: Invalid ip provided") ip = "" return ip
def join(): global temp_name try: temp_name = sys.argv[1] + '.md' except IndexError: exit('usage: tmpm template') if os.path.exists(config['template_root'] + temp_name): with open(config['template_root'] + temp_name, 'r') as file: import re from rich.prompt import Prompt content = re.findall('##(.*?)\n.*?```.*?\n(.*?)```', file.read(), re.S) for i, v in enumerate(content): QproDefaultConsole.print('[%d] %s' % (i + 1, v[0].strip()), end=' ' if i + 1 % 10 else '\n') indx = int(Prompt.ask(('%sChoose' if user_lang != 'zh' else '%s选择') % ('\n' if len(content) % 10 else ''))) - 1 content = content[indx] with open(config['compile_filename'], 'r') as file: content = file.read().replace('__TMPM__', content[1].strip()) with open(config['compile_filename'], 'w') as file: file.write(content) else: return QproDefaultConsole.print( QproErrorString, ( 'No template named: {temp_name}' if user_lang != 'zh' else '没有模板: {temp_name}' ).format(temp_name=temp_name) )