Query: write a function that outputs a table in python

Relevant code:
def get_table(ports):
    """
    This function returns a pretty table used to display the port results.

    :param ports: list of found ports
    :return: the table to display
    """
    table = PrettyTable(["Name", "Port", "Protocol", "Description"])
    table.align["Name"] = "l"
    table.align["Description"] = "l"
    table.padding_width = 1

    for port in ports:
        table.add_row(port)

    return table

Similar but not relevant code:
def inventory(self, source_id, fetch=False, fmt='table'):
        """
        Prints a summary of all objects in the database. Input string or list of strings in **ID** or **unum**
        for specific objects.

        Parameters
        ----------
        source_id: int
            The id from the SOURCES table whose data across all tables is to be printed.
        fetch: bool
            Return the results.
        fmt: str
            Returns the data as a dictionary, array, or astropy.table given 'dict', 'array', or 'table'

        Returns
        -------
        data_tables: dict
            Returns a dictionary of astropy tables with the table name as the keys.

        """
        data_tables = {}

        t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table')
        all_tables = t['name'].tolist()
        for table in ['sources'] + [t for t in all_tables if
                                    t not in ['sources', 'sqlite_sequence']]:

            try:

                # Get the columns, pull out redundant ones, and query the table for this source's data
                t = self.query("PRAGMA table_info({})".format(table), fmt='table')
                columns = np.array(t['name'])
                types = np.array(t['type'])

                if table == 'sources' or 'source_id' in columns:

                    # If printing, only get simple data types and exclude redundant 'source_id' for nicer printing
                    if not fetch:
                        columns = columns[
                            ((types == 'REAL') | (types == 'INTEGER') | (types == 'TEXT')) & (columns != 'source_id')]

                    # Query the table
                    try:
                        id = 'id' if table.lower() == 'sources' else 'source_id'
                        data = self.query(
                            "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id),
                            fmt='table')

                        if not data and table.lower() == 'sources':
                            print(
                            'No source with id {}. Try db.search() to search the database for a source_id.'.format(
                                source_id))

                    except:
                        data = None

                    # If there's data for this table, save it
                    if data:
                        if fetch:
                            data_tables[table] = self.query(
                                "SELECT {} FROM {} WHERE {}={}".format(','.join(columns), table, id, source_id), \
                                fetch=True, fmt=fmt)
                        else:
                            data = data[[c.lower() for c in columns]]
                            pprint(data, title=table.upper())

                else:
                    pass

            except:
                print('Could not retrieve data from {} table.'.format(table.upper()))

        if fetch: return data_tables

Similar but not relevant code:
def get_latex_table(self, parameters=None, transpose=False, caption=None,
                        label="tab:model_params", hlines=True, blank_fill="--"):  # pragma: no cover
        """ Generates a LaTeX table from parameter summaries.

        Parameters
        ----------
        parameters : list[str], optional
            A list of what parameters to include in the table. By default, includes all parameters
        transpose : bool, optional
            Defaults to False, which gives each column as a parameter, each chain (framework)
            as a row. You can swap it so that you have a parameter each row and a framework
            each column by setting this to True
        caption : str, optional
            If you want to generate a caption for the table through Python, use this.
            Defaults to an empty string
        label : str, optional
            If you want to generate a label for the table through Python, use this.
            Defaults to an empty string
        hlines : bool, optional
            Inserts ``\\hline`` before and after the header, and at the end of table.
        blank_fill : str, optional
            If a framework does not have a particular parameter, will fill that cell of
            the table with this string.

        Returns
        -------
        str
            the LaTeX table.
        """
        if parameters is None:
            parameters = self.parent._all_parameters
        for p in parameters:
            assert isinstance(p, str), \
                "Generating a LaTeX table requires all parameters have labels"
        num_parameters = len(parameters)
        num_chains = len(self.parent.chains)
        fit_values = self.get_summary(squeeze=False)
        if label is None:
            label = ""
        if caption is None:
            caption = ""

        end_text = " \\\\ \n"
        if transpose:
            column_text = "c" * (num_chains + 1)
        else:
            column_text = "c" * (num_parameters + 1)

        center_text = ""
        hline_text = "\\hline\n"
        if hlines:
            center_text += hline_text + "\t\t"
        if transpose:
            center_text += " & ".join(["Parameter"] + [c.name for c in self.parent.chains]) + end_text
            if hlines:
                center_text += "\t\t" + hline_text
            for p in parameters:
                arr = ["\t\t" + p]
                for chain_res in fit_values:
                    if p in chain_res:
                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))
                    else:
                        arr.append(blank_fill)
                center_text += " & ".join(arr) + end_text
        else:
            center_text += " & ".join(["Model"] + parameters) + end_text
            if hlines:
                center_text += "\t\t" + hline_text
            for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):
                arr = ["\t\t" + name]
                for p in parameters:
                    if p in chain_res:
                        arr.append(self.get_parameter_text(*chain_res[p], wrap=True))
                    else:
                        arr.append(blank_fill)
                center_text += " & ".join(arr) + end_text
        if hlines:
            center_text += "\t\t" + hline_text
        final_text = get_latex_table_frame(caption, label) % (column_text, center_text)

        return final_text