Python texttable.Texttable() Examples

The following are 30 code examples of texttable.Texttable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module texttable , or try the search function .
Example #1
Source File: bundle.py    From hammr with Apache License 2.0 6 votes vote down vote up
def do_list(self, args):
        try:
            #call UForge API
            printer.out("Getting all your bundles ...")
            bundles = self.api.Users(self.login).Mysoftware.Getall()
            bundles = bundles.mySoftwareList.mySoftware
            if bundles is None or len(bundles) == 0:
                printer.out("No bundles available")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t", "t","t","t","t"])
                table.header(["Id", "Name", "Version", "Description", "Category", "Size", "Imported"])
                bundles = generics_utils.order_list_object_by(bundles, "name")
                for bundle in bundles:
                    category = ""
                    if bundle.category is not None:
                        category = bundle.category.name
                    table.add_row([bundle.dbId, bundle.name, bundle.version, bundle.description, category, size(bundle.size), "X" if bundle.imported else ""])
                print table.draw() + "\n"
                printer.out("Found "+str(len(bundles))+" bundles")

            return 0
        except Exception as e:
            return handle_uforge_exception(e) 
Example #2
Source File: vt.py    From VirusTotalApi with MIT License 6 votes vote down vote up
def pretty_print_special(rows, headers, sizes=False, align=False, email=False):

    try:
        tab = tt.Texttable()

        if email:
            tab.set_deco(tt.Texttable.HEADER)

        tab.add_rows(rows)

        if sizes:
            tab.set_cols_width(sizes)

        if align:
            tab.set_cols_align(align)

        tab.header(headers)

        print('\n')
        print(tab.draw())

    except Exception as e:
        print('Report me plz')
        print(e) 
Example #3
Source File: __init__.py    From disk_perf_test_tool with Apache License 2.0 6 votes vote down vote up
def format_for_console(cls, data):
        success_vals = []
        duration_vals = []
        count = 0
        for res in data[0]:
            msgs, success, duration = res.raw_result.strip().split('\n')
            count += int(msgs)
            success_vals.append(float(success))
            duration_vals.append(float(duration))

        totalt = max(duration_vals)
        totalms = int(count / totalt)
        sucesst = int(sum(success_vals) / len(success_vals))
        tab = texttable.Texttable(max_width=120)
        tab.set_deco(tab.HEADER | tab.VLINES | tab.BORDER)
        tab.header(["Bandwidth m/s", "Success %"])
        tab.add_row([totalms, sucesst])
        return tab.draw() 
Example #4
Source File: select.py    From Vaile with GNU General Public License v3.0 6 votes vote down vote up
def display(i, names: list, descriptions: list, values: list):
    for k in i:
        names.append(k)
        descriptions.append(i[k][0])
        values.append(i[k][1])

    t = table.Texttable()
    headings = ["Name", "Desc.", "Val"]
    t.header(headings)
    #t.set_chars(["-"," ","+","~"])
    t.set_deco(table.Texttable.BORDER)
    for row in zip(names, descriptions, values):
        t.add_row(row)
    s = t.draw()
    print(s + "\n")
    return names, descriptions, values 
Example #5
Source File: __init__.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def autodoc_fields(declaration_cls, model_cls):
    """Produces autodocumentation table for the fields.

    Exposed as a function in order to be reusable by a simple export,
    e.g., from anyblok.mixin.
    """
    if not has_sql_fields([model_cls]):
        return ''

    rows = [['Fields', '']]
    rows.extend([x, y.autodoc()]
                for x, y in get_fields(model_cls).items())
    table = Texttable(max_width=0)
    table.set_cols_valign(["m", "t"])
    table.add_rows(rows)
    return table.draw() + '\n\n' 
Example #6
Source File: diff.py    From formica with MIT License 6 votes vote down vote up
def __generate_table(header, current, new):
    changes = DeepDiff(current, new, ignore_order=False, report_repetition=True, verbose_level=2, view="tree")
    table = Texttable(max_width=200)
    table.set_cols_dtype(["t", "t", "t", "t"])
    table.add_rows([["Path", "From", "To", "Change Type"]])
    print_diff = False
    processed_changes = __collect_changes(changes)
    for change in processed_changes:
        print_diff = True
        path = re.findall("\\['?([\\w-]+)'?\\]", change.path)
        table.add_row([" > ".join(path), change.before, change.after, change.type.title().replace("_", " ")])
    logger.info(header + " Diff:")
    if print_diff:
        logger.info(table.draw() + "\n")
    else:
        logger.info("No Changes found" + "\n") 
Example #7
Source File: cli.py    From formica with MIT License 6 votes vote down vote up
def resources(args):
    from texttable import Texttable

    client = cloudformation_client()
    paginator = client.get_paginator("list_stack_resources").paginate(StackName=args.stack)

    table = Texttable(max_width=150)
    table.add_rows([RESOURCE_HEADERS])

    for page in paginator:
        for resource in page["StackResourceSummaries"]:
            table.add_row(
                [
                    resource["LogicalResourceId"],
                    resource["PhysicalResourceId"],
                    resource["ResourceType"],
                    resource["ResourceStatus"],
                ]
            )

    logger.info(table.draw() + "\n") 
Example #8
Source File: helper.py    From diff2vec with GNU General Public License v3.0 6 votes vote down vote up
def generation_tab_printer(read_times, generation_times):
    """
    Function to print the time logs in a nice tabular format.
    :param read_times: List of reading times.
    :param generation_times: List of generation times.
    """
    t = Texttable()
    t.add_rows([["Metric", "Value"],
                ["Mean graph read time:", np.mean(read_times)],
                ["Standard deviation of read time.", np.std(read_times)]])
    print(t.draw())
    t = Texttable()
    t.add_rows([["Metric", "Value"],
                ["Mean sequence generation time:", np.mean(generation_times)],
                ["Standard deviation of generation time.", np.std(generation_times)]])
    print(t.draw()) 
Example #9
Source File: Helper.py    From m2em with MIT License 6 votes vote down vote up
def printFeeds():

    table = texttable.Texttable()
    table.set_deco(texttable.Texttable.HEADER)
    table.set_cols_dtype(['i',  # int
                          't',])  # text
    table.header(["ID", "URL"])

    # Connect
    db.connection()

    for row in Feeds.select():
        table.add_row([row.feedid, row.url])

    # Close connection
    db.close()

    logging.info(table.draw()) 
Example #10
Source File: user.py    From hammr with Apache License 2.0 6 votes vote down vote up
def do_info(self, args):
        try:
            #call UForge API
            printer.out("Getting user ["+self.login+"] ...")
            user = self.api.Users(self.login).Get()
            if user is None:
                printer.out("user "+ self.login +"does not exist", printer.ERROR)
            else:
                table = Texttable(200)
                table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
                table.header(["Login", "Email", "Lastname",  "Firstname",  "Created", "Active", "Promo Code", "Creation Code"])
                table.add_row([user.loginName, user.email, user.surname , user.firstName, user.created.strftime("%Y-%m-%d %H:%M:%S"), "X", user.promoCode, user.creationCode])
                print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_info()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #11
Source File: Helper.py    From m2em with MIT License 6 votes vote down vote up
def printFilters():

    table = texttable.Texttable()
    table.set_deco(texttable.Texttable.HEADER)
    table.set_cols_dtype(['i',  # int
                          't',])  # text
    table.header(["ID", "FILTER"])

    # Connect
    db.connection()

    for row in Filter.select():
        table.add_row([row.filterid, row.filtervalue])

    # Close connection
    db.close()

    logging.info(table.draw()) 
Example #12
Source File: Helper.py    From m2em with MIT License 6 votes vote down vote up
def printUsers():

    table = texttable.Texttable()
    table.set_deco(texttable.Texttable.HEADER)
    table.set_cols_dtype(['i',  # int
                          't',
                          't',
                          't',
                          't'])  # text
    table.header(["ID", "USERNAME", "EMAIL", "KINDLE EMAIL", "SEND EBOOK"])

    db.connection()
    for user in User.select():
        if user.sendtokindle == 1:
            sendstatus = "YES"
        else:
            sendstatus = "NO"
        table.add_row([user.userid, user.name, user.email, user.kindle_mail, sendstatus])
    db.close()
    logging.info(table.draw()) 
Example #13
Source File: utils.py    From GraphWaveletNeuralNetwork with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    keys = sorted(args.keys())
    t = Texttable()
    t.add_rows([["Parameter", "Value"]])
    t.add_rows([[k.replace("_", " ").capitalize(), args[k]] for k in keys])
    print(t.draw()) 
Example #14
Source File: template.py    From hammr with Apache License 2.0 5 votes vote down vote up
def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            #call UForge API
            printer.out("Searching template with id ["+doArgs.id+"] ...")
            myAppliance = self.api.Users(self.login).Appliances(doArgs.id).Get()
            if myAppliance is None or type(myAppliance) is not Appliance:
                printer.out("Template not found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
                table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
                table.add_row([myAppliance.dbId, myAppliance.name, str(myAppliance.version), myAppliance.distributionName+" "+myAppliance.archName,
                               myAppliance.created.strftime("%Y-%m-%d %H:%M:%S"), myAppliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), len(myAppliance.imageUris.uri),myAppliance.nbUpdates, "X" if myAppliance.imported else "", "X" if myAppliance.shared else ""])
                print table.draw() + "\n"

                if doArgs.no_confirm:
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete template with id "+str(myAppliance.dbId)):
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #15
Source File: account.py    From hammr with Apache License 2.0 5 votes vote down vote up
def do_delete(self, args):
        try:
            # add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            # call UForge API
            printer.out("Searching account with id [" + doArgs.id + "] ...")
            account = self.api.Users(self.login).Accounts(doArgs.id).Get()
            if account is None:
                printer.out("No Account available", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t"])
                table.header(["Id", "Name", "Type", "Created"])
                table.add_row(
                    [account.dbId, account.name, account.targetPlatform.name, account.created.strftime("%Y-%m-%d %H:%M:%S")])
                print table.draw() + "\n"
                if doArgs.no_confirm:
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete account with id " + str(account.dbId)):
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #16
Source File: os.py    From hammr with Apache License 2.0 5 votes vote down vote up
def do_search(self, args):
        try:
            #add arguments
            doParser = self.arg_search()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            #call UForge API
            printer.out("Search package '"+doArgs.pkg+"' ...")
            distribution = self.api.Distributions(Id=doArgs.id).Get()
            printer.out("for OS '"+distribution.name+"', version "+distribution.version)
            pkgs = self.api.Distributions(Id=distribution.dbId).Pkgs.Getall(Query="name=="+doArgs.pkg)
            pkgs = pkgs.pkgs.pkg
            if pkgs is None or len(pkgs) == 0:
                printer.out("No package found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t"])
                table.header(["Name", "Version", "Arch", "Release", "Build date", "Size", "FullName"])
                pkgs = generics_utils.order_list_object_by(pkgs, "name")
                for pkg in pkgs:
                    table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size), pkg.fullName])
                print table.draw() + "\n"
                printer.out("Found "+str(len(pkgs))+" packages")
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_search()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #17
Source File: os.py    From hammr with Apache License 2.0 5 votes vote down vote up
def do_list(self, args):
        try:
            #call UForge API
            printer.out("Getting distributions for ["+self.login+"] ...")
            distributions = self.api.Users(self.login).Distros.Getall()
            distributions = distributions.distributions
            if distributions is None or not hasattr(distributions, "distribution"):
                printer.out("No distributions available")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t", "t"])
                table.header(["Id", "Name", "Version", "Architecture", "Release Date", "Profiles"])
                distributions = generics_utils.order_list_object_by(distributions.distribution, "name")
                for distribution in distributions:
                    profiles = self.api.Distributions(Id=distribution.dbId).Profiles.Getall()
                    profiles = profiles.distribProfiles.distribProfile
                    if len(profiles) > 0:
                        profile_text=""
                        for profile in profiles:
                            profile_text+=profile.name+"\n"
                        table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", profile_text])
                    else:
                        table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", "-"])
                print table.draw() + "\n"
                printer.out("Found "+str(len(distributions))+" distributions")
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #18
Source File: helpers.py    From TENE with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    keys = sorted(args.keys())
    t = Texttable()
    rows = [["Parameter", "Value"]]
    rows = rows + [[k.replace("_", " ").capitalize(), args[k]] for k in keys]
    t.add_rows(rows)
    print(t.draw()) 
Example #19
Source File: domainhunter.py    From domainhunter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def drawTable(header,data):
    
    data.insert(0,header)
    t = Texttable(max_width=maxwidth)
    t.add_rows(data)
    t.header(header)
    
    return(t.draw()) 
Example #20
Source File: platform.py    From hammr with Apache License 2.0 5 votes vote down vote up
def do_list(self, args):
        try:
            printer.out("Getting target platform :")
            targetPlatformsUser = self.api.Users(self.login).Targetplatforms.Getall()
            if targetPlatformsUser is None or len(targetPlatformsUser.targetPlatforms.targetPlatform) == 0:
                printer.out("There is no target platform")
                return 0
            else:
                targetPlatformsUser = generics_utils.order_list_object_by(
                    targetPlatformsUser.targetPlatforms.targetPlatform, "name")
                printer.out("Target platform list:")
                table = Texttable(200)
                table.set_cols_align(["c", "c", "c", "c"])
                table.header(["Id", "Name", "Type", "Access"])
                for item in targetPlatformsUser:
                    if item.access:
                        access = "X"
                    else:
                        access = ""
                    table.add_row([item.dbId, item.name, item.type, access])
                print table.draw() + "\n"
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e) 
Example #21
Source File: helpers.py    From TADW with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    keys = sorted(args.keys())
    t = Texttable() 
    t.add_rows([["Parameter", "Value"]])
    t.add_rows([[k.replace("_", " ").capitalize(), args[k]] for k in keys])
    print(t.draw()) 
Example #22
Source File: utils.py    From APPNP with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    keys = sorted(args.keys())
    t = Texttable()
    t.add_rows([["Parameter", "Value"]] + [[k.replace("_", " ").capitalize(), args[k]] for k in keys])
    print(t.draw()) 
Example #23
Source File: utils.py    From MixHop-and-N-GCN with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    keys = sorted(args.keys())
    t = Texttable()
    t.add_rows([["Parameter", "Value"]])
    t.add_rows([[k.replace("_", " ").capitalize(), args[k]] for k in keys])
    print(t.draw()) 
Example #24
Source File: helpers.py    From BoostedFactorization with GNU General Public License v3.0 5 votes vote down vote up
def tab_printer(args):
    """
    Function to print the logs in a nice tabular format.
    :param args: Parameters used for the model.
    """
    args = vars(args)
    t = Texttable()
    t.add_rows([["Parameter", "Value"]])
    t.add_rows([[k.replace("_", " ").capitalize(), v] for k, v in args.items()])
    print(t.draw()) 
Example #25
Source File: select.py    From Vaile with GNU General Public License v3.0 5 votes vote down vote up
def listdisplay(names, descs):
    t = table.Texttable()
    headings = ["Modvle", "Desc."]
    t.header(headings)
    t.set_chars(["—","|","+","—"])
    t.set_deco(table.Texttable.HEADER)
    for row in zip(names, descs):
        t.add_row(row)
    s = t.draw()
    print("\n" + s + "\n") 
Example #26
Source File: Helper.py    From m2em with MIT License 5 votes vote down vote up
def printChaptersAll():

    # Make the query
    db.connection()
    chapters = Chapter.select().order_by(Chapter.chapterid)
    db.close()

    table = texttable.Texttable(max_width=120)
    table.set_deco(texttable.Texttable.HEADER)
    table.set_cols_align(["l", "l", "l", "l", "l", "l"])
    table.set_cols_dtype(['i',  # int
                          't',
                          't',
                          't',
                          't',
                          't'])  # text
    table.header (["ID", "MANGA", "CHAPTER", "CHAPTERNAME", "RSS ORIGIN", "SEND STATUS"])


    logging.info("Listing all chapters:")
    for row in chapters:
        # Rename row[8]
        if row.issent == 1:
            sendstatus = "SENT"
        else:
            sendstatus = "NOT SENT"
        table.add_row([row.chapterid, row.manganame, row.chapter, row.title+"\n", str(row.origin), sendstatus])
    logging.info(table.draw()) 
Example #27
Source File: tadw.py    From TADW with GNU General Public License v3.0 5 votes vote down vote up
def loss_printer(self):
        """
        Function to print the losses in a nice tabular format.
        """
        t = Texttable()
        t.add_rows([["Iteration", "Main loss", "Regul loss I.", "Regul loss II."]])
        t.add_rows(self.losses)
        print(t.draw()) 
Example #28
Source File: stack_set.py    From formica with MIT License 5 votes vote down vote up
def accounts_table(accounts_map):
    table = Texttable(max_width=150)
    table.set_cols_dtype(["t", "t"])
    table.add_rows([["Account", "Regions"]])

    for account, regions in accounts_map.items():
        table.add_row([account, ", ".join(regions)])

    logger.info(table.draw() + "\n") 
Example #29
Source File: cli.py    From formica with MIT License 5 votes vote down vote up
def stacks(args):
    from texttable import Texttable

    client = AWS.current_session().client("cloudformation")
    stacks = client.describe_stacks()
    table = Texttable(max_width=150)
    table.add_rows([STACK_HEADERS])

    for stack in stacks["Stacks"]:
        table.add_row(
            [stack["StackName"], stack["CreationTime"], stack.get("LastUpdatedTime", ""), stack["StackStatus"]]
        )

    logger.info("Current Stacks:\n" + table.draw() + "\n") 
Example #30
Source File: helpers.py    From BoostedFactorization with GNU General Public License v3.0 5 votes vote down vote up
def simple_print(name, value):
    """
    Print a loss value in a text table.
    :param name: Name of loss.
    :param loss: Loss value.
    """
    print("\n")
    t = Texttable()
    t.add_rows([[name, value]])
    print(t.draw())