7.5. Better Outputs

7.5.1. How to Strip Outputs and Execute Interactive Code in a Python Script

!pip install strip-interactive

Have you ever seen a tutorial with an interactive Python code and wished to execute it in a Python script like above?

It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. That is why I created strip-interactive.

from strip_interactive import run_interactive

code = """
>>> import numpy as np
>>> print(np.array([1,2,3]))
[1 2 3]
>>> print(np.array([4,5,6]))
[4 5 6]
"""

clean_code = run_interactive(code)
[1 2 3]
[4 5 6]

Link to the article about strip-interactive.

Link to strip-interactive.

7.5.2. Pyfiglet: Make Large and Unique Letters Out of Ordinary Text in Python

!pip install pyfiglet

If you want to make large and unique letters out of ordinary text using Python, try pyfiglet. Below are some outputs of pyfiglet:

import pyfiglet
from termcolor import colored, cprint

out = pyfiglet.figlet_format("Hello")
print(out)
 _   _      _ _       
| | | | ___| | | ___  
| |_| |/ _ \ | |/ _ \ 
|  _  |  __/ | | (_) |
|_| |_|\___|_|_|\___/ 
                      
out = pyfiglet.figlet_format("Hello", font='slant')
print(out)
    __  __     ____    
   / / / /__  / / /___ 
  / /_/ / _ \/ / / __ \
 / __  /  __/ / / /_/ /
/_/ /_/\___/_/_/\____/ 
                       
cprint(pyfiglet.figlet_format('Hello', font='bell'), 'blue')
 __  __         .    .         
 |   |    ___   |    |     __. 
 |___|  .'   `  |    |   .'   \
 |   |  |----'  |    |   |    |
 /   /  `.___, /\__ /\__  `._.'
                               

This could be used as the welcome message for your Python package 🙂

Link to pyfiglet.

Link to termcolor.

7.5.3. Typer: Build a Command-Line Interface in a Few Lines of Code

!pip install typer 

The last thing you want to happen is to have users dig into your code to run it. Is there a way that users can insert arguments into your code on the command line?

That is when Typer comes in handy. Typer allows you to build a command-line interface in a few lines of code based on Python-type hints.

For example, in a file named typer_example, write:

import typer 

def process_data(data: str, version: int):
    print(f'Processing {data},' 
          f'version {version}')

if __name__ == '__main__':
    typer.run(process_data)

On your terminal, type:

python typer_example.py data 1

And you should see an output like below:

!python typer_example.py data 1
Processing data,version 1

Link to Typer.

My full article about Typer.