Skip to content

Instantly share code, notes, and snippets.

@hoel-bagard
Last active April 5, 2022 08:34
Show Gist options
  • Select an option

  • Save hoel-bagard/68e8f45696289ce2ae686a73ba56dc30 to your computer and use it in GitHub Desktop.

Select an option

Save hoel-bagard/68e8f45696289ce2ae686a73ba56dc30 to your computer and use it in GitHub Desktop.
Notes used during the inhouse presentation on python packages.

Create the required files

mkdir inhouse_python_packages
cd inhouse_python_packages
mkdir clean_print
touch clean_print/clean_print.py
touch clean_print/__init__.py
touch setup.py

Add code to the files

In clean_print/clean_print.py:

from shutil import get_terminal_size


def clean_print(msg: str, fallback: tuple[int, int] = (156, 38), end='\n'):
    r"""Function that prints the given string to the console and erases any previous print made on the same line.

    Args:
        msg (str): String to print to the console
        fallback (tuple, optional): Size of the terminal to use if it cannot be determined by shutil
                                    (if using Windows for example)
        end (str): What to add at the end of the print. Usually '\n' (new line), or '\r' (back to the start of the line)
    """
    print(msg + ' ' * (get_terminal_size(fallback=fallback).columns - len(msg)), end=end, flush=True)

In clean_print/__init__.py:

__all__ = ["clean_print"]

from .clean_print import clean_print

In setup.py:

import setuptools


setuptools.setup(
    name="clean_print_<your_name>",
    version="0.0.1",
    description="Print that can erase lines.",
    # long_description=open("README.md", encoding="utf-8").read(),
    # long_description_content_type='text/markdown',
    # url="https://github.com/<username>/<repo>",
    author="X Y",
    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10"
    ],
    keywords="print, inhouse",
    packages=["clean_print"],
    python_requires=">=3.8",
)

Test it

virtualenv venv
source venv/bin/activate
pip install .
ipython
from clean_print import clean_print
clean_print("a")

PyPi

Got to https://test.pypi.org/ and register.
Then build and upload the package with:

python setup.py sdist
pip install twine
twine upload --repository testpypi dist/*

● And finally install it and test it:

virtualenv venv
source venv/bin/activate
pip install --index-url https://test.pypi.org/simple/ clean_print
ipython
from clean_print import clean_print
clean_print("a", end="\r")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment