Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7 changes: 7 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
include LICENSE
include README.md
include requirements.txt
include MANIFEST.in
recursive-include cli_ui *.py
recursive-include examples *.py
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
165 changes: 165 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# python-cli-ui

[![Python](https://img.shields.io/pypi/pyversions/cli-ui.svg)](https://pypi.org/project/cli-ui)
[![PyPI](https://img.shields.io/pypi/v/cli-ui.svg)](https://pypi.org/project/cli-ui/)
[![License](https://img.shields.io/github/license/your-tools/python-cli-ui.svg)](https://github.com/your-tools/python-cli-ui/blob/main/LICENSE)

Tools for nice user interfaces in the terminal.

## Note

This project was originally hosted on the [TankerHQ](https://github.com/TankerHQ) organization, which was my employer from 2016 to 2021. They kindly agreed to give back ownership of this project to me. Thanks!

## Features

- **Colored output**: Easy to use color constants and formatting
- **User input**: Ask questions, get choices, passwords
- **Progress indication**: Show progress with dots, counters, and progress bars
- **Tables**: Display data in nicely formatted tables
- **Timers**: Time operations with context managers or decorators
- **Cross-platform**: Works on Linux, macOS, and Windows

## Installation

```bash
pip install cli-ui
```

## Quick Start

```python
import cli_ui

# Coloring
cli_ui.info(
"This is", cli_ui.red, "red", cli_ui.reset,
"and this is", cli_ui.bold, "bold"
)

# User input
with_sugar = cli_ui.ask_yes_no("With sugar?", default=False)

fruits = ["apple", "orange", "banana"]
selected_fruit = cli_ui.ask_choice("Choose a fruit", choices=fruits)

# Progress
list_of_things = ["foo", "bar", "baz"]
for i, thing in enumerate(list_of_things):
cli_ui.info_count(i, len(list_of_things), thing)

# Tables
headers = ["name", "score"]
data = [
[("John", cli_ui.bold), (10, cli_ui.green)],
[("Jane", cli_ui.bold), (5, cli_ui.green)],
]
cli_ui.info_table(data, headers=headers)
```

## API Overview

### Colors and Formatting

Available colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`
Available formatting: `bold`, `faint`, `standout`, `underline`, `blink`, `overline`, `reset`

### Information Functions

- `info(*tokens, **kwargs)` - Print informative message
- `info_1(*tokens, **kwargs)` - Important info with "::" prefix
- `info_2(*tokens, **kwargs)` - Secondary info with "=>" prefix
- `info_3(*tokens, **kwargs)` - Detailed info with "*" prefix
- `info_section(*tokens, **kwargs)` - Section header with underline
- `debug(*tokens, **kwargs)` - Debug message (only shown if verbose=True)

### Error Functions

- `warning(*tokens, **kwargs)` - Print warning message
- `error(*tokens, **kwargs)` - Print error message
- `fatal(*tokens, exit_code=1, **kwargs)` - Print error and exit

### Progress Functions

- `dot(last=False, fileobj=sys.stdout)` - Print progress dot
- `info_count(i, n, *rest, **kwargs)` - Show counter with message
- `info_progress(prefix, value, max_value)` - Show percentage progress

### User Input Functions

- `ask_string(*question, default=None)` - Ask for string input
- `ask_password(*question)` - Ask for password (hidden input)
- `ask_yes_no(*question, default=False)` - Ask yes/no question
- `ask_choice(*prompt, choices, func_desc=None, sort=True)` - Choose from list
- `select_choices(*prompt, choices, func_desc=None, sort=True)` - Select multiple

### Table Functions

- `info_table(data, headers=(), fileobj=sys.stdout)` - Display formatted table

### Utility Functions

- `indent(text, num=2)` - Indent text by number of spaces
- `tabs(num)` - Generate tab spacing
- `did_you_mean(message, user_input, choices)` - Suggest corrections

### Configuration

```python
cli_ui.setup(
verbose=False, # Show debug messages
quiet=False, # Hide info messages
color="auto", # Color mode: "auto", "always", "never"
title="auto", # Terminal title updates
timestamp=False # Add timestamps to messages
)
```

### Timer Context Manager

```python
# As context manager
with cli_ui.Timer("doing something"):
do_something()

# As decorator
@cli_ui.Timer("processing")
def process_data():
# ... processing code
pass
```

## Testing Support

For testing code that uses cli-ui:

```python
from cli_ui.tests import MessageRecorder

def test_my_function(message_recorder):
message_recorder.start()
my_function() # calls cli_ui.info("something")
assert message_recorder.find("something")
message_recorder.stop()
```

## Examples

See the `examples/` directory for:
- Basic usage examples
- Threading examples
- Async/await examples

## Requirements

- Python 3.7+
- colorama>=0.4.1
- tabulate>=0.8.3
- unidecode>=1.0.23

## License

BSD 3-Clause License. See LICENSE file for details.

## Contributing

Contributions welcome! Please see the contributing guidelines in the repository.
38 changes: 6 additions & 32 deletions cli_ui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import io
import os
import re
import shutil
import sys
import time
import traceback
Expand All @@ -23,14 +22,14 @@

# Global variable to store configuration

CONFIG: Dict[str, ConfigValue] = {
CONFIG = {
"verbose": os.environ.get("VERBOSE"),
"quiet": False,
"color": "auto",
"title": "auto",
"timestamp": False,
"record": False, # used for testing
}
} # type: Dict[str, ConfigValue]


# used for testing
Expand Down Expand Up @@ -189,7 +188,7 @@ def process_tokens(
"""
# Flatten the list of tokens in case some of them are of
# class UnicodeSequence:
flat_tokens: List[Token] = []
flat_tokens = [] # type: List[Token]
for token in tokens:
if isinstance(token, UnicodeSequence):
flat_tokens.extend(token.tuple())
Expand Down Expand Up @@ -331,14 +330,7 @@ def dot(*, last: bool = False, fileobj: FileObj = sys.stdout) -> None:
info(".", end=end, fileobj=fileobj)


def erase_last_line() -> None:
terminal_size = shutil.get_terminal_size()
info(" " * terminal_size.columns, end="\r")


def info_count(
i: int, n: int, *rest: Token, one_line: bool = False, **kwargs: Any
) -> None:
def info_count(i: int, n: int, *rest: Token, **kwargs: Any) -> None:
"""Display a counter before the rest of the message.

``rest`` and ``kwargs`` are passed to :func:`info`
Expand All @@ -347,14 +339,10 @@ def info_count(

:param i: current index
:param n: total number of items
:param one_line: force all messages to be printed on one line
"""
num_digits = len(str(n))
counter_format = "(%{}d/%d)".format(num_digits)
counter_str = counter_format % (i + 1, n)
if one_line:
kwargs["end"] = "\r"
erase_last_line()
info(green, "*", reset, counter_str, reset, *rest, **kwargs)


Expand Down Expand Up @@ -603,11 +591,7 @@ def select_choices(
continue

try:
res = (
list(itemgetter(*index)(choices))
if len(index) > 1
else [itemgetter(*index)(choices)]
)
res = list(itemgetter(*index)(choices))
except Exception:
info("Please enter valid selection number(s)")
continue
Expand Down Expand Up @@ -723,21 +707,11 @@ def main_demo() -> None:
info()
info_section(bold, "progress info")

info_2("3 things")
list_of_things = ["foo", "bar", "baz"]
for i, thing in enumerate(list_of_things):
info_count(i, len(list_of_things), thing)
info()

info_2("3 other things on one line")
list_of_things = ["spam", "eggs", "butter"]
for i, thing in enumerate(list_of_things):
time.sleep(0.5)
info_count(i, len(list_of_things), thing, one_line=True)
info()

info()
info_2("Doing someting that takes some time")
time.sleep(0.5)
info_progress("Doing something", 5, 20)
time.sleep(0.5)
Expand All @@ -761,4 +735,4 @@ def main() -> None:


if __name__ == "__main__":
main()
main()
9 changes: 9 additions & 0 deletions cli_ui/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
"""
Main entry point for cli_ui module when called with python -m cli_ui
"""

from . import main

if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion cli_ui/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .conftest import MessageRecorder # noqa
from .conftest import MessageRecorder # noqa
2 changes: 1 addition & 1 deletion cli_ui/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ def message_recorder(request: Any) -> Iterator[MessageRecorder]:
recorder = MessageRecorder()
recorder.start()
yield recorder
recorder.stop()
recorder.stop()
9 changes: 1 addition & 8 deletions cli_ui/tests/test_cli_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,13 +345,6 @@ def func_desc(fruit: Fruit) -> str:
assert m.call_count == 3


def test_select_choices_single_select() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = ["1"]
res = cli_ui.select_choices("Select a animal", choices=["cat", "dog", "cow"])
assert res == ["cat"]


def test_select_choices_empty_input() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = [""]
Expand Down Expand Up @@ -425,4 +418,4 @@ def foo() -> None:
cli_ui.red,
"error when fooing\n",
"ZeroDivisionError",
)
)
2 changes: 1 addition & 1 deletion examples/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ async def main():


if __name__ == "__main__":
asyncio.run(main())
asyncio.run(main())
Loading