Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
box.py
#1
this is the completed command/module i wrote, referred to here.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
file          box.py
purpose       Output the contents one or more files in a +- style text box.
note          Use '-' or '+' for STDIN.  Defaults to STDIN if no name given.
note          Precede a filename with '=' to bypass parsing names.
note          The name will be included in the top line if the width is OK.
email         10054452614123394844460370234029112340408691

The intent is that this command works correctly under both Python 2 and
Python 3.  Please report failures or code improvement to the author.
"""

__license__ = """
Copyright (C) 2016, by Phil D. Howard - all other rights reserved

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

The author may be contacted by decoding the number
10054452614123394844460370234029112340408691
(provu igi la numeron al duuma)
"""

from sys import argv, exc_info, stderr, stdin, stdout


def boxit( *a, **aa ):
    """
function      boxit
purpose       Add a +- style text box around a list of strings
usage         newarray = boxit( array [ , titlestring ] | [ title=titlestring ] )
"""
    if len(a) < 1:
        return None
    array = a[0]
    title = None
    if len(a) > 1:
        title = a[1]
    if 'title' in aa:
        title = aa['title']
    width = max( [ len(row) for row in array ] )
    last = first = '+-' + '-'*width + '-+'
    if title != None:
        if len(title)+6 < width:
            first = '+-'+('--<'+title+'>').ljust(width,'-')+'-+'
    return [first] + ['| '+row.ljust(width)+' |' for row in array] + [last]


def main( args ):
    error_count = 0
    names = ['-'] if len(args) < 2 else args[1:]
    for name in names:
        use_stdin = name.lower() in ('-','+','-stdin','+stdin')
        if name[0] == '=':
            name = name[1:]
        try:
            file = stdin if use_stdin else open( name )
            if file == None:
                print( 'unable to open file', repr( name ), file=stderr )
                error_count += 1
        except IOError:
            print( 'IOError while opening file', repr( name ), file=stderr )
    if error_count > 0: return 'aborting due to {} errors'.format(repr(error_count))
    for name in names:
        use_stdin = name.lower() in ('-','+','-stdin','stdin')
        if name[0] == '=':
            name = name[1:]
        file = stdin if use_stdin else open( name )
        contents = file.readlines()
        if use_stdin:
            name = 'STDIN'
        else:
            file.close()
        box = boxit( [ row.rstrip() for row in contents ], title=name )
        for row in box:
            print( row )
    return 0


if __name__ == '__main__':
    try:
        result = main( argv )
        stdout.flush()
    except KeyboardInterrupt:
        result = 141
        print( '' )
    except IOError:
        result = 142
    try:
        exit( int( result ) )
    except ValueError:
        print( str( result ), file=stderr )
        exit( 1 )
    except TypeError:
        if result == None:
            exit( 0 )
        exit( 255 )

# EOF

line 38 can be removed Big Grin
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Could you include some demo code?
Reply
#3
the main() function is demo code for the boxit() function. it runs as a command, reads a file (or stdin) collecting it as a list of strings, then passes that list to boxit() getting the result list of strings returned, which it prints.

the real meat of this code is lines 39 to 58.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020