Skip to main content

jblib

Author: Justin Bard

This module was written to minimize the need to write the functions I use often.

INSTALL: python3 -m pip install jblib


The source code can be viewed here: https://github.com/ANamelessDrake/jblib

More of my projects can be found here: http://justbard.com


from jblib import cd

    class cd()

        Example:
            with cd(directory):
                print (os.getcwd())

            print (os.getcwd()) ## Back at the originating directory on exit

from jblib import Color, BgColor, jbcolor, gradient, rainbow, fade, cycle, pulse, border

    Modern Terminal Color Utilities

    CLASSES:
        Color   -- Foreground color and text attribute constants for f-string use
        BgColor -- Background color constants for f-string use

    FUNCTIONS:
        jbcolor(text, fg=None, bg=None, bold=False, dim=False, italic=False,
                underline=False, reverse=False, strikethrough=False)
        gradient(text, start, end, bold=False)
        rainbow(text, bold=False)
        fade(text, start, end, bold=False)
        cycle(text, colors, bold=False)
        pulse(text, start, end, cycles=3, speed=0.05, steps=20, bold=False)
        border(content, title=None, color=None, title_color=None, padding=1,
               vpadding=0, width=None, rounded=False, fullwidth=False, margin=1)

    AVAILABLE COLORS:
        Standard:  BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, TEAL, WHITE
        Bright:    BRIGHT_BLACK, BRIGHT_RED, BRIGHT_GREEN, BRIGHT_YELLOW,
                   BRIGHT_BLUE, BRIGHT_PURPLE, BRIGHT_TEAL, BRIGHT_WHITE
        RGB Named: ORANGE
        Attributes (Color only): BOLD, DIM, ITALIC, UNDERLINE, REVERSE, STRIKETHROUGH
        Reset: OFF / RESET

    EXAMPLES:

        ## Color constants in f-strings
        print(f"{Color.RED}red text{Color.OFF}")
        print(f"{Color.BOLD}{Color.ORANGE}bold orange{Color.OFF}")
        print(f"{BgColor.YELLOW}{Color.BLACK}highlighted{Color.OFF}")

        ## jbcolor() with auto-reset -- named colors or RGB tuples
        print(jbcolor("Error", fg="red", bold=True))
        print(jbcolor("Custom", fg=(128, 0, 255), bg=(0, 0, 0)))
        print(jbcolor("Warning", fg="black", bg="yellow"))

        ## Concatenation works naturally
        msg = "Result: " + jbcolor("PASS", fg="green", bold=True) + " - done"

        ## Gradient -- smooth fade from one color to another
        print(gradient("Hello World", "red", "blue"))
        print(gradient("Smooth", (255, 0, 0), (0, 0, 255), bold=True))

        ## Rainbow -- full spectrum across characters
        print(rainbow("Rainbow Text!"))

        ## Fade -- color to color and back (bounce effect)
        print(fade("Breathing effect", "red", "blue"))

        ## Cycle -- hard switch through a list of colors per character
        print(cycle("Alternating!", ["red", "blue", "green"]))
        print(cycle("Flag", [(255, 0, 0), (255, 255, 255), (0, 0, 255)]))

        ## Pulse -- animated in-place color transition
        pulse("ALERT", "red", "yellow", cycles=5)
        pulse("Loading...", "purple", "teal", cycles=0)  ## Infinite (Ctrl+C to stop)

        ## Border -- wrap content in a Unicode box
        print(border("Hello World", title="Greeting", color="blue"))
        print(border("Spacious", title="Info", color="teal", rounded=True, vpadding=1))
        print(border("Line 1\nLine 2\nLine 3", title="Status", color="green", rounded=True))
        print(border(jbcolor("PASS", fg="green", bold=True), title="Result", color="green"))
        print(border("Full width box", title="Wide", color="blue", fullwidth=True))
        print(border("Custom margin", title="Indented", color="green", fullwidth=True, margin=4))

(Deprecated) Python 3.8 or earlier: from jblib import hilight

(Deprecated) Python 3.9 or later: from jblib import hilightV2

    DEPRECATED: Use Color, BgColor, and jbcolor() instead.

    class hilight(string).color(highlight=True, bold=True)

    EXAMPLE:
        print (hilight("Hello World").red(bold=True))

        Or you could make an object:
            text = hilight("Bar")

            print ("Foo "+text.blue())

        To return the original string:
            print (text.string)

    COLORS:
        red
        green
        yellow
        blue
        purple
        teal
        white

    FUN FACTS:
        * This class is loosely based off the very first bit of python code I ever wrote. It was initially created while teaching myself python.
        * This module was intentionally misspelled to shorten the keystrokes needed during use.

from jblib import convert_module

    Module to convert various data

            def convert_time_from_seconds(seconds_given)
                Converts a seconds into minutes, hours and days.

            def IP2Int(ip)
                Converts a IPv4 address to a interger - This is useful to store IP addresses in databases

            def Int2IP(ipnum)
                Converts a interger back to an IPv4 address

            def urlcode(url, encode=False)
                Wrapper for urllib.parse.quote and urllib.parse.unquote.
                From urllib docs - Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of URL.
                - https://docs.python.org/3.1/library/urllib.parse.html?highlight=urllib#urllib.parse.quote

from jblib import HTMLgen

        Basic HTML generator
        02/09/2019

        class HTMLgen(head=False, tail=False, lang="en", docType="html")

        FUNCTIONS:
            title(self, title, scripts=None, css=None)
            body.add(content)
            tag(tag, content=False, close=True, cssclass=None)
            image(src, alt=None, srcset=None, height=None, width=None, style=None, cssclass=None)
            br() <-- Returns a </ br> tag
            div(cssclass) <-- Not yet implemented
            table() -- Class Object
                table.add_row()
                table.produce_table()

        EXAMPLE:
            page = HTMLgen(True, True)
            page.title("This is the page Title", scripts="foo.js bar.js", css="styles.css nav.css")
            page.body.add(page.image("images/frontpage.jpg", width="100%"))
            page.body.add(page.tag("h1", "This is a header line"))
            page.body.add("This is another line")

            ## Creating a table
            test_table = HTMLgen.table()
            test_table.add_row(["column data 1", "column data 2", "column data 3"])
            test_table.add_row(["column data 4", "column data 5", "column data 6"])

            ## And finally we add the table to the rest of the page
            page.body.add(test_table.produce_table())


            page.return_html()

            ```
                <!DOCTYPE html>
                <html lang="en>
                    <head>
                        <title>This is the page Title</title>
                        <link rel="stylesheet" href="styles.css">
                        <link rel="stylesheet" href="nav.css">
                        <script src="foo.js"></script>
                        <script src="bar.js"></script>
                    </head>
                <body>
                    <img src="images/frontpage.jpg" width="100%">
                    <h1>This is a header line</h1>
                    This is another line
                   	<table>
                        <tr>
                            <td>column data 1</td><td>column data 2</td><td>column data 3</td>
                        </tr>
                        <tr>
                            <td>column data 4</td><td>column data 5</td><td>column data 6</td>
                        </tr>

                    </table>

                </body>
                </html>
            ```

from jblib import progress_bar

    Progress Bar
    02/25/2019

    FUNCTIONS:
        progress_bar(progress, barLength=50, text_field="Progress")

    EXAMPLE:
        counter = 0
        for i in range(100):
            counter += 1
            i = counter/100
            progress_bar(i, 50)
            sleep(0.1)

    Progress: [#########################-------------------------] 50.0%

from jblib import colored_progress_bar

    Colored Progress Bar
    10/10/2023

    FUNCTIONS:
        colored_progress_bar(progress, barLength=50, text_field="Progress")

    EXAMPLE:
        counter = 0
        for i in range(100):
            counter += 1
            i = counter/100
            colored_progress_bar(i, 50)
            sleep(0.1)

    Progress: [#########################-------------------------] 50.0%

from jblib import TransferProgress

    Transfer Progress
    10/09/2026

    CLASS:
        TransferProgress(total, label="Download", color=True, stream=sys.stderr,
                         quiet=False, unit="bytes", colors=("red", "green"))

    METHODS:
        progress(n)        -- add n (boto3 transfer Callback compatible)
        update(n)          -- add n
        set(value)         -- set the current value
        finish()           -- print the final line with average speed and elapsed time

    DESCRIPTION:
        A thread safe progress line for downloads, uploads, hashing and unpacking.
        On a terminal it redraws one line in place (about 10 times a second, 100%
        is always drawn) with a gradient bar (red to green by default), percent, amount done, a speed
        smoothed over the last few seconds and an ETA, sized to the terminal width.
        When the stream is not a terminal, or NO_COLOR is set, it prints a plain
        line every 10% with no escape codes and no carriage returns.
        quiet=True prints nothing. unit="items" shows counts instead of bytes.
        Also works as a context manager (finish() is called on a clean exit).
        colors sets the bar gradient: a (start, end) pair, or three or more stops
        spaced evenly. Each stop is a color name or an (r, g, b) tuple, as jbcolor
        accepts; an unknown name raises ValueError.

    EXAMPLE:
        ## boto3 calls the callback from several threads; that is safe
        with TransferProgress(size, label="Download") as progress:
            s3.download_file(bucket, key, path, Callback=progress)

        ## Custom gradients: names, RGB tuples, or three or more stops
        TransferProgress(size, colors=("blue", "teal"))
        TransferProgress(size, colors=((255, 80, 0), (0, 160, 255)))
        TransferProgress(size, colors=("red", "yellow", "green"))

        ## Counting items
        with TransferProgress(len(members), label="Unpack", unit="items") as progress:
            for member in members:
                archive.extract(member, target)
                progress(1)

    Download ████████████████▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬  42%  575.1 / 1368.0 MB  48.2 MB/s  ETA 0:16
    Download ████████████████████████████████████████ 100%  1368.0 / 1368.0 MB  avg 47.9 MB/s  in 0:28

from jblib import supports_color

    FUNCTIONS:
        supports_color(stream=sys.stdout)

    DESCRIPTION:
        Returns False when the stream is not a TTY, when NO_COLOR is set to a
        non-empty value, or when TERM=dumb. Otherwise True.

    EXAMPLE:
        label = jbcolor("PASS", fg="green") if supports_color() else "PASS"

from jblib import format_bytes, format_duration

    FUNCTIONS:
        format_bytes(n)            -- binary units: "512 B", "1.5 KB", "575.1 MB", "1.3 GB"
        format_duration(seconds)   -- "M:SS", or "H:MM:SS" from one hour up; "--:--" when unknown

    EXAMPLE:
        format_bytes(1536)         ## '1.5 KB'
        format_duration(65)        ## '1:05'
        format_duration(3725)      ## '1:02:05'

from jblib import StreamToLogger

    DESCRIPTION:
        Fake file-like stream object that redirects writes to a logger instance.

    CLASS:
        StreamToLogger(object)
    EXAMPLE:
        if log_enabled: ## If true, all standard output and standard error to the console will be disabled
            # create logger
            logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y%m%d %H:%M:%S', filename=log_file)
            logger = logging.getLogger(__name__)
            logger.setLevel(logging.DEBUG)

            logger.propagate = False
            fh = logging.FileHandler(log_file, "a")
            fh.setLevel(logging.DEBUG)
            formatter = logging.Formatter(fmt='%(asctime)s - %(message)s', datefmt='%Y%m%d %H:%M:%S')
            fh.setFormatter(formatter)
            logger.addHandler(fh)
            keep_fds = [fh.stream.fileno()]

            stdout_logger = logging.getLogger('STDOUT')
            sl = StreamToLogger(stdout_logger, logging.INFO)
            sys.stdout = sl

            stderr_logger = logging.getLogger('STDERR')
            sle = StreamToLogger(stderr_logger, logging.ERROR)
            sys.stderr = sle

from jblib import build_date_array

    Build Date Arrays
    02/27/2019

    FUNCTIONS:
        build_date_array(days=1, start_date=str(datetime.date.today()), date_format='%Y-%m-%d', mon=True, tues=True, wed=True, thur=True, fri=True, sat=True, sun=True, weekend=True):

    EXAMPLE:
        dates = build_date_array(days=7, weekend=False)
        dates
            ['2019-02-27', '2019-02-28', '2019-03-01', '2019-03-02', '2019-03-03', '2019-03-05', '2019-03-06']

Metadata

Release files for jblib 1.12.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jblib 1.12.0
File Size Uploaded
jblib-1.12.0.tar.gz 25.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for jblib 1.12.0
File Interpreter ABI Platform
jblib-1.12.0-py3-none-any.whl Python 3 none any Details

Total release size: 49.3 kB

Release files / jblib-1.12.0.tar.gz

Download URL jblib-1.12.0.tar.gz
Size 25.3 kB
Tags Source
SHA-256 checksum
How to use checksums
77ef797de672778549eb75b542547a73abef9ff26acd115e269461dee06c4466
BLAKE2b-256 checksum
How to use checksums
63d91702605939e886006adde97ac7b2c31a2a45c6aeaceb5957dcbca9883003
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / jblib-1.12.0-py3-none-any.whl

Download URL jblib-1.12.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ed1c8650524acaf4652fa05686111be13466db609754717f38d8fd884437e519
BLAKE2b-256 checksum
How to use checksums
706b75525691c10df4a0a4d260c6f45ac3ae2a6ce84dd0ea6720b8bdfb2504e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page