Python print headers

16 Python code examples are found related to " print headers". 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.
Example 1
Source File: interface.py    From aria2p with ISC License 6 votes vote down vote up
def print_headers(self):
        """Print the headers (columns names)."""
        self.scroller.set_scroll(self.x_scroll)
        x, y, c = self.x_offset, self.y_offset, 0

        for column_name in self.columns_order:
            column = self.columns[column_name]
            palette = self.palettes["focused_header"] if c == self.sort else self.palettes["header"]

            if column.padding == "100%":
                header_string = f"{column.header}"
                fill_up = " " * max(0, self.width - x - len(header_string))
                written = self.scroller.print_at(header_string, x, y, palette)
                self.scroller.print_at(fill_up, x + written, y, self.palettes["header"])

            else:
                header_string = f"{column.header:{column.padding}} "
                written = self.scroller.print_at(header_string, x, y, palette)

            x += written
            c += 1 
Example 2
Source File: command_line.py    From mrcfile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_headers(names=None, print_file=None):
    """
    Print the MRC header contents from a list of files.
    
    This function opens files in permissive mode to allow headers of invalid
    files to be examined.
    
    Args:
        names: A list of file names. If not given or :data:`None`, the names
            are taken from the command line arguments.
        print_file: The output text stream to use for printing the headers.
            This is passed directly to the ``print_file`` argument of
            :meth:`~mrcfile.mrcobject.MrcObject.print_header`. The default is
            :data:`None`, which means output will be printed to
            :data:`sys.stdout`.
    """
    if names is None:
        names = sys.argv[1:]
    for name in names:
        with mrcfile.open(name, permissive=True, header_only=True) as mrc:
            mrc.print_header(print_file=print_file) 
Example 3
Source File: print_headers.py    From genmod with MIT License 6 votes vote down vote up
def print_headers(head, outfile=None, silent=False):
    """
    Print the vcf headers.
    
    If a result file is provided headers will be printed here, otherwise
    they are printed to stdout.
    
    Args:
        head (HeaderParser): A vcf header object
        outfile (FileHandle): A file handle
        silent (Bool): If nothing should be printed.
        
    """
    for header_line in head.print_header():
        
        if outfile:
            outfile.write(header_line+'\n')
        else:
            if not silent:
                print(header_line)
    return 
Example 4
Source File: utils.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def print_response_headers(headers, file=None):
    """Write the response's headers to stdout in a human-friendly way.

    :type headers: :class:`httplib2.Response`, or :class:`dict`
    """
    file = sys.stdout if file is None else file

    # Function to change headers like "transfer-encoding" into
    # "Transfer-Encoding".
    def cap(header):
        return "-".join(part.capitalize() for part in header.split("-"))

    # Format string to prettify reporting of response headers.
    form = "%%%ds: %%s" % (max(len(header) for header in headers) + 2)
    # Print the response.
    for header in sorted(headers):
        print(form % (cap(header), headers[header]), file=file) 
Example 5
Source File: fitsheader.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_headers_traditional(args):
    """Prints FITS header(s) using the traditional 80-char format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    """
    for idx, filename in enumerate(args.filename):  # support wildcards
        if idx > 0 and not args.keywords:
            print()  # print a newline between different files

        formatter = None
        try:
            formatter = HeaderFormatter(filename)
            print(formatter.parse(args.extensions,
                                  args.keywords,
                                  args.compressed), end='')
        except OSError as e:
            log.error(str(e))
        finally:
            if formatter:
                formatter.close() 
Example 6
Source File: textmodetrees.py    From udapi-python with GNU General Public License v3.0 5 votes vote down vote up
def print_headers(self, root):
        """Print sent_id, text and other comments related to the tree."""
        if self.print_sent_id:
            print('# sent_id = ' + root.address())
        if self.print_text:
            print("# text = " + (root.get_sentence() if root.is_root() else root.compute_text()))
        if self.print_comments and root.comment:
            print('#' + self.colorize_comment(root.comment.rstrip().replace('\n', '\n#'))) 
Example 7
Source File: HtmlTableParser.py    From table-extractor with GNU General Public License v3.0 5 votes vote down vote up
def print_headers(self, tab):
        """
        Method used to print in the console the header cells found and refined before make a single row from all the
         header's rows.

        :param tab: Table object containing the headers to print out
        :return:
        """
        print("These are the headers found: ")
        # Iterate over table headers
        for row in tab.headers:
            # Iterate over header cells
            for th_cell in row:
                # Print text for that header
                print(th_cell['th']) 
Example 8
Source File: headers.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def print_all_headers(uc, base_addr):
    print_dos_header(uc, base_addr)
    print()
    print_pe_header(uc, base_addr)
    print()
    print_opt_header(uc, base_addr)
    print()
    print_section_table(uc, base_addr)
    print()
    print_iat(uc, base_addr) 
Example 9
Source File: mpyq.py    From heroes-of-the-storm-replay-parser with MIT License 5 votes vote down vote up
def print_headers(self):
        print "MPQ archive header"
        print "------------------"
        for key, value in self.header.iteritems():
            if key == "user_data_header":
                continue
            print "{0:30} {1!r}".format(key, value)
        if self.header.get('user_data_header'):
            print
            print "MPQ user data header"
            print "--------------------"
            for key, value in self.header['user_data_header'].iteritems():
                print "{0:30} {1!r}".format(key, value)
        print 
Example 10
Source File: readelf.py    From ppci with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_program_headers(program_headers):
    """ Print the program headers """
    print("Program headers:")
    print("  Type             Offset         VirtAddr         PhysAddr")
    print("              FileSiz           MemSiz  Flags  Align")
    for program_header in program_headers:
        p_type = program_header["p_type"]
        if p_type < ProgramHeaderType.LOOS:
            p_type = ProgramHeaderType(p_type).name

        print(
            "  {:16} 0x{:016x} 0x{:016x} 0x{:016x}".format(
                p_type,
                program_header["p_offset"],
                program_header["p_vaddr"],
                program_header["p_paddr"],
            )
        )
        print(
            "                 0x{:016x} 0x{:016x}  {}  0x{:04x}".format(
                program_header["p_filesz"],
                program_header["p_memsz"],
                program_header["p_flags"],
                program_header["p_align"],
            )
        )
    print() 
Example 11
Source File: readelf.py    From ppci with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_section_headers(elf_file):
    """ Print the section headers in a nice overview """
    print("Section headers:")
    print("  [Nr] Name              Type             Address           Offset")
    print("       Size              Entsize          Flags   Link Info  Align")
    for index, section in enumerate(elf_file.sections):
        sh_type = section.header["sh_type"]
        if sh_type < SectionHeaderType.LOOS:
            sh_type = SectionHeaderType(sh_type).name
        print(
            "  [{:2d}] {:16s}  {:16} {:016x}  {:016x}".format(
                index,
                elf_file.get_str(section.header["sh_name"]),
                sh_type,
                section.header["sh_addr"],
                section.header["sh_offset"],
            )
        )
        print(
            "       {:016x}  {:016x} {} {} {} {}".format(
                section.header["sh_size"],
                section.header["sh_entsize"],
                section.header["sh_flags"],
                section.header["sh_link"],
                section.header["sh_info"],
                section.header["sh_addralign"],
            )
        )
    print() 
Example 12
Source File: template.py    From plaitpy with MIT License 5 votes vote down vote up
def print_headers(self):
        self.csv_writer = None
        if CSV:
            self.csv_writer = csv.DictWriter(sys.stdout, fieldnames=self.headers)
            self.csv_writer.writeheader() 
Example 13
Source File: BaseWeb.py    From CDSS with GNU General Public License v3.0 5 votes vote down vote up
def printHeaders(self):
        """Print HTTP headers before printing any body text"""
        print("Content-type: text/html")
        # Set any Cookies
        print(self.getCookies()) 
Example 14
Source File: fitsheader.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def print_headers_as_table(args):
    """Prints FITS header(s) in a machine-readable table format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    """
    tables = []
    # Create a Table object for each file
    for filename in args.filename:  # Support wildcards
        formatter = None
        try:
            formatter = TableHeaderFormatter(filename)
            tbl = formatter.parse(args.extensions,
                                  args.keywords,
                                  args.compressed)
            if tbl:
                tables.append(tbl)
        except OSError as e:
            log.error(str(e))  # file not found or unreadable
        finally:
            if formatter:
                formatter.close()

    # Concatenate the tables
    if len(tables) == 0:
        return False
    elif len(tables) == 1:
        resulting_table = tables[0]
    else:
        from astropy import table
        resulting_table = table.vstack(tables)
    # Print the string representation of the concatenated table
    resulting_table.write(sys.stdout, format=args.table) 
Example 15
Source File: mpyq.py    From Blender-WMO-import-export-scripts with GNU General Public License v3.0 5 votes vote down vote up
def print_headers(self):
        print("MPQ archive header")
        print("------------------")
        for key, value in self.header.items():
            if key == "user_data_header":
                continue
            print("{0:30} {1!r}".format(key, value))
        if self.header.get('user_data_header'):
            print()
            print("MPQ user data header")
            print("--------------------")
            for key, value in self.header['user_data_header'].items():
                print("{0:30} {1!r}".format(key, value))
        print() 
Example 16
Source File: fitsheader.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def print_headers_as_comparison(args):
    """Prints FITS header(s) with keywords as columns.

    This follows the dfits+fitsort format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    """
    from astropy import table
    tables = []
    # Create a Table object for each file
    for filename in args.filename:  # Support wildcards
        formatter = None
        try:
            formatter = TableHeaderFormatter(filename, verbose=False)
            tbl = formatter.parse(args.extensions,
                                  args.keywords,
                                  args.compressed)
            if tbl:
                # Remove empty keywords
                tbl = tbl[np.where(tbl['keyword'] != '')]
            else:
                tbl = table.Table([[filename]], names=('filename',))
            tables.append(tbl)
        except OSError as e:
            log.error(str(e))  # file not found or unreadable
        finally:
            if formatter:
                formatter.close()

    # Concatenate the tables
    if len(tables) == 0:
        return False
    elif len(tables) == 1:
        resulting_table = tables[0]
    else:
        resulting_table = table.vstack(tables)

    # If we obtained more than one hdu, merge hdu and keywords columns
    hdus = resulting_table['hdu']
    if np.ma.isMaskedArray(hdus):
        hdus = hdus.compressed()
    if len(np.unique(hdus)) > 1:
        for tab in tables:
            new_column = table.Column(
                ['{}:{}'.format(row['hdu'], row['keyword']) for row in tab])
            tab.add_column(new_column, name='hdu+keyword')
        keyword_column_name = 'hdu+keyword'
    else:
        keyword_column_name = 'keyword'

    # Check how many hdus we are processing
    final_tables = []
    for tab in tables:
        final_table = [table.Column([tab['filename'][0]], name='filename')]
        if 'value' in tab.colnames:
            for row in tab:
                if row['keyword'] in ('COMMENT', 'HISTORY'):
                    continue
                final_table.append(table.Column([row['value']],
                                                name=row[keyword_column_name]))
        final_tables.append(table.Table(final_table))
    final_table = table.vstack(final_tables)
    # Sort if requested
    if args.fitsort is not True:  # then it must be a keyword, therefore sort
        final_table.sort(args.fitsort)
    # Reorganise to keyword by columns
    final_table.pprint(max_lines=-1, max_width=-1)