def print_table(table, col_names, title): result = VeryPrettyTable() result.title = title result.field_names = col_names for row in table: result.add_row([format(i, ".2f") for i in row]) print(result)
def setup_table(pv, pypi, inc): """ Renders Table containing data elements via cli stdout """ # setup table x = VeryPrettyTable(border=tablespec['border'], header=tablespec['header'], padding_width=tablespec['padding']) title_cell1 = 'Current Project' title_cell2 = 'pypi.python.org' title_cell3 = 'Next Increment' x.field_names = [ titlec + title_cell1 + frame, titlec + title_cell2 + frame, titlec + title_cell3 + frame, ] # cell max width x.max_width[titlec + title_cell1 + frame] = column_widths['project'] x.max_width[titlec + title_cell2 + frame] = column_widths['pypi'] x.max_width[titlec + title_cell3 + frame] = column_widths['incremental'] # cell min = max width x.min_width[titlec + title_cell1 + frame] = column_widths['project'] x.min_width[titlec + title_cell2 + frame] = column_widths['pypi'] x.min_width[titlec + title_cell3 + frame] = column_widths['incremental'] # cell alignment x.align[titlec + title_cell1 + frame] = 'c' x.align[titlec + title_cell2 + frame] = 'c' x.align[titlec + title_cell3 + frame] = 'c' # populate table # key credentials are either expired (age > KEYAGE_MAX) or valid project_version = c.BOLD + c.BRIGHT_BLUE + pv + rst pypi_version = c.BOLD + c.BRIGHT_BLUE + pypi + rst inc_version = c.BOLD + c.BRIGHT_BLUE + inc + rst x.add_row([ rst + project_version + frame, rst + pypi_version + frame, rst + inc_version + frame, ]) # Table vtab_int = 20 vtab = '\t'.expandtabs(vtab_int) msg = '{}PROJECT VERSION SOURCES{}{}|{}'.format(btext, rst + frame, ' ' + vtab, rst) print_header(title=msg, indent=10, spacing=vtab_int) display_table(x, tabspaces=4) return _postprocessing()
def _list(self, args): """List the supported CVEs. """ table = VeryPrettyTable() table.field_names = ["CVE", "Description", "Versions affected"] for exploit in self.exploits: table.add_row([exploit[0], exploit[1], exploit[2]]) self.logger.handle(table.get_string(), None)
def userdata_lookup(debug): """ Summary. Instance Profile role user selection Returns: iam instance profile role ARN (str) or None """ # setup table x = VeryPrettyTable(border=True, header=True, padding_width=2) field_max_width = 70 x.field_names = [ bd + '#' + frame, bd + 'Filename' + frame, bd + 'Path' + frame, bd + 'CreateDate' + frame, bd + 'LastModified' + frame ] # cell alignment x.align[bd + '#' + frame] = 'c' x.align[bd + 'Filename' + frame] = 'c' x.align[bd + 'Path' + frame] = 'l' x.align[bd + 'CreateDate' + frame] = 'c' x.align[bd + 'LastModified' + frame] = 'c' filenames = source_local_userdata() paths = source_local_userdata(paths=True) ctimes = [time.ctime(os.path.getctime(x)) for x in paths] mtimes = [time.ctime(os.path.getmtime(x)) for x in paths] # populate table lookup = {} for index, path in enumerate(paths): lookup[index] = paths[index] x.add_row( [ rst + userchoice_mapping(index) + '.' + frame, rst + filenames[index] + frame, rst + path + frame, rst + ctimes[index] + frame, rst + mtimes[index] + frame ] ) # Table showing selections print(f'\n\tUserdata Scripts (local filesystem: ~/.config/ec2tools/userdata)\n'.expandtabs(26)) display_table(x, tabspaces=4) return choose_resource(lookup)
def table(data): x = VeryPrettyTable() x.field_names = HEADERS temp_kelvin = data['main']['temp'] temp_celcius = celcius(temp_kelvin) temp_farenheit = farenheit(temp_kelvin) x.add_row([ data['name'], temp_celcius, temp_farenheit, data['weather'][0]['main'], data['weather'][0]['description'] ]) return x
def wordpress(self): from veryprettytable import VeryPrettyTable x = VeryPrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide",1295, 1158259, 600.5]) x.add_row(["Brisbane",5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) return print(x)
def ip_lookup(profile, region, debug): """ Summary. Instance Profile role user selection Returns: iam instance profile role ARN (str) or None """ now = datetime.datetime.utcnow() # setup table x = VeryPrettyTable(border=True, header=True, padding_width=2) field_max_width = 70 x.field_names = [ bd + '#' + frame, bd + 'InstanceProfileName' + frame, bd + 'RoleArn' + frame, bd + 'CreateDate' + frame ] # cell alignment x.align[bd + '#' + frame] = 'c' x.align[bd + 'InstanceProfileName' + frame] = 'l' x.align[bd + 'RoleArn' + frame] = 'l' x.align[bd + 'CreateDate' + frame] = 'c' roles = source_instanceprofiles(parse_profiles(profile)) # populate table lookup = {} for index, iprofile in enumerate(roles): lookup[index] = iprofile['Arn'] x.add_row([ rst + str(index) + '.' + frame, rst + iprofile['InstanceProfileName'] + frame, rst + iprofile['Arn'][:field_max_width] + frame, rst + iprofile['CreateDate'] + frame ]) # add default choice (None) lookup[index + 1] = None x.add_row([ rst + str(index + 1) + '.' + frame, rst + 'Default' + frame, None, rst + now.strftime('%Y-%m-%dT%H:%M:%S') + frame ]) # Table showing selections print(f'\n\tInstance Profile Roles (global directory)\n'.expandtabs(26)) display_table(x, tabspaces=4) return choose_resource(lookup, selector='numbers', default=(index + 1))
def get_subnet(profile, region, debug): """ Summary. Returns subnet user selection in given region Args: :profile (str): profile_name from local awscli configuration :region (str): AWS region code Returns: subnet id chosen by user """ # setup table x = VeryPrettyTable(border=True, header=True, padding_width=2) field_max_width = 30 x.field_names = [ bd + '#' + frame, bd + 'SubnetId' + frame, bd + 'AZ' + frame, bd + 'CIDR' + frame, bd + 'Ip Assign' + frame, bd + 'State' + frame, bd + 'VpcId' + frame ] #subnets = get_contents(account_file)[region]['Subnets'] subnets = profile_subnets(profile, region) # populate table lookup = {} for index, row in enumerate(subnets): for k, v in row.items(): lookup[index] = k x.add_row([ rst + userchoice_mapping(index) + '.' + frame, rst + k + frame, rst + v['AvailabilityZone'] + frame, rst + v['CidrBlock'] + frame, rst + v['IpAddresses'] + frame, rst + v['State'] + frame, rst + v['VpcId'] + frame ]) # Table showing selections print(f'\n\tSubnets in region {bd + region + rst}\n'.expandtabs(30)) display_table(x) return choose_resource(lookup)
def keypair_lookup(profile, region, debug): """ Summary. Returns name of keypair user selection in given region Args: :profile (str): profile_name from local awscli configuration :region (str): AWS region code Returns: keypair name chosen by user """ # setup table x = VeryPrettyTable(border=True, header=True, padding_width=2) field_max_width = 30 x.field_names = [bd + '#' + frame, bd + 'Keypair' + frame] # cell alignment x.align[bd + '#' + frame] = 'c' x.align[bd + 'Keypair' + frame] = 'l' keypairs = profile_keypairs(parse_profiles(profile), region)[region] # populate table lookup = {} for index, keypair in enumerate(keypairs): lookup[index] = keypair x.add_row([ rst + userchoice_mapping(index) + '.' + frame, rst + keypair + frame ]) # Table showing selections print(f'\n\tKeypairs in region {bd + region + rst}\n'.expandtabs(26)) display_table(x, tabspaces=16) return choose_resource(lookup)
def format_dict_to_table(data: dict, delete=None, show_type=False): delete = delete or [] table = VeryPrettyTable() field_names = ["key", "value"] if show_type: field_names += ["type"] table.field_names = field_names table.align['key'] = 'r' table.align['value'] = 'l' if show_type: table.align['type'] = 'l' for _key, _value in data.items(): if _key in delete: continue row = [_key, _value] if not show_type else [_key, _value, f"{type(_value)}"] table.add_row(row) return f"{table.get_string()}"
def changelog(self): """ You need to create in your rule table with next structure: Version Reason Author Date Comment separator for fields specified by cl_separator :return: table with changes :rtype VeryPrettyTable() """ prettytable = VeryPrettyTable() changelog = [] for i in range(0, len(self.allrule)): if self.allrule[i].lower().startswith('\'change log'): self.log_start = i if self.allrule[i].startswith('\'_') and i > self.log_start: self.log_end = i break self.log_start += self.cl_intendant # intending from change log string to table for i in range(self.log_start, self.log_end): self.allrule[i] = self.allrule[i].replace(' ', '\t') comment_line = [ item for item in self.allrule[i][1:].strip().split( self.cl_separator) if item ] version = comment_line.pop(0) reason = comment_line.pop(0) author = comment_line.pop(0) data = comment_line.pop(0) comment = " ".join(comment_line) changelog.append([version, reason, author, data, comment]) prettytable.field_names = [ "Version", 'Reason', 'Author', 'Date', 'Comment' ] prettytable.align['Comment'] = 'l' for change in changelog: prettytable.add_row(change) return prettytable
def create(self, departure, arrival): table = VeryPrettyTable() table.field_names = ['Departure',' ','Arrival',' '] for de,ar, in zip(departure,arrival): table.add_row([de,departure[de],ar,arrival[ar]]) return table
for field in courses.columns.values: print(field, end="\t\t") print() for index, row in courses.iterrows(): for col in row: print(col, end="\t\t") print() if __name__ == '__main__': while True: dept_no = input("請輸入系所代號 (如要離開,請輸入-1) : ") if (dept_no == "-1"): break try: crawler = NckuCourseCrawler(dept_no=dept_no) html = crawler.get_raw_HTML() parser = NckuCourseParser(html) parser.include_fields = ["系號", "序號", "餘額", "課程名稱(連結課程地圖)", "學分", "教師姓名*:主負責老師", "時間"] courses = parser.parse(sort=True) table = VeryPrettyTable() table.field_names = courses.columns.values for i in courses.iterrows(): table.add_row(i[1]) print(table) except NoCourseAvailableError as e: print(e)
def sg_lookup(profile, region, debug): """ Summary. Returns securitygroup user selection in given region Args: :profile (str): profile_name from local awscli configuration :region (str): AWS region code Returns: securitygroup ID chosen by user """ padding = 2 field_max_width = 50 max_gn, max_desc = 10, 10 # starting value to find max length of a table field (chars) x = VeryPrettyTable(border=True, header=True, padding_width=padding) sgs = profile_securitygroups(profile, region) for index, row in enumerate(sgs): for k, v in row.items(): if len(v['GroupName']) > max_gn: max_gn = len(v['GroupName']) if len(v['Description']) > max_desc: max_desc = len(v['GroupName']) if debug: print('max_gn = {}'.format(max_gn)) print('max_desc = {}'.format(max_desc)) # GroupName header tabspaces_gn = int(max_gn / 4) - int(len('GroupName') / 2) + padding tab_gn = '\t'.expandtabs(tabspaces_gn) # Description header tabspaces_desc = int(max_desc / 4) - int(len('Description') / 2) + padding tab_desc = '\t'.expandtabs(tabspaces_desc) x.field_names = [ bd + ' # ' + frame, bd + 'GroupId' + frame, tab_gn + bd + 'GroupName' + frame, bd + 'VpcId' + frame, tab_desc + bd + 'Description' + frame ] # cell alignment x.align = 'c' x.align[tab_gn + bd + 'GroupName' + frame] = 'l' x.align[tab_desc + bd + 'Description' + frame] = 'l' # populate table lookup = {} for index, row in enumerate(sgs): for k, v in row.items(): lookup[index] = k x.add_row([ rst + userchoice_mapping(index) + '.' + frame, rst + k + frame, rst + v['GroupName'][:field_max_width] + frame, rst + v['VpcId'] + frame, rst + v['Description'][:field_max_width] + frame ]) # Table showing selections print( f'\n\tSecurity Groups in region {bd + region + rst}\n'.expandtabs(30)) display_table(x) return choose_resource(lookup)
def consoleLabel(deduper, additional_columns=[]): # pragma: no cover ''' Command line interface for presenting and labeling training pairs by the user Argument : A deduper object ''' finished = False use_previous = False fields = unique(field.field for field in deduper.data_model.primary_fields) buffer_len = 1 # Max number of previous operations examples_buffer = [] uncertain_pairs = [] while not finished: if use_previous: record_pair, _ = examples_buffer.pop(0) use_previous = False else: if not uncertain_pairs: uncertain_pairs = deduper.uncertainPairs() record_pair = uncertain_pairs.pop() n_match = (len(deduper.training_pairs['match']) + sum(label == 'match' for _, label in examples_buffer)) n_distinct = (len(deduper.training_pairs['distinct']) + sum(label == 'distinct' for _, label in examples_buffer)) x = VeryPrettyTable() columns = fields + additional_columns x.field_names = columns x.align = "l" for pair in record_pair: x.add_row(list(pair[field] for field in columns)) print(x) print("{0}/10 positive, {1}/10 negative".format(n_match, n_distinct), file=sys.stderr) print('Do these records refer to the same thing?', file=sys.stderr) valid_response = False user_input = '' while not valid_response: if examples_buffer: prompt = '(y)es / (n)o / (u)nsure / (f)inished / (p)revious' valid_responses = {'y', 'n', 'u', 'f', 'p'} else: prompt = '(y)es / (n)o / (u)nsure / (f)inished' valid_responses = {'y', 'n', 'u', 'f'} print(prompt, file=sys.stderr) user_input = input() if user_input in valid_responses: valid_response = True if user_input == 'y': examples_buffer.insert(0, (record_pair, 'match')) elif user_input == 'n': examples_buffer.insert(0, (record_pair, 'distinct')) elif user_input == 'u': examples_buffer.insert(0, (record_pair, 'uncertain')) elif user_input == 'f': print('Finished labeling', file=sys.stderr) finished = True elif user_input == 'p': use_previous = True uncertain_pairs.append(record_pair) if len(examples_buffer) > buffer_len: record_pair, label = examples_buffer.pop() if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples) for record_pair, label in examples_buffer: if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples)
from veryprettytable import VeryPrettyTable table = VeryPrettyTable() table.field_names = ["animal", "ferocity"] table.add_row(["wolverine", 100]) table.add_row(["grizzly", 87]) table.add_row(["cat", -1]) table.add_row(["dolphin", 63]) table.header = False print(table)