Skip to main content

Elegant interactive command-line interface tool library, Python implementation of Inquirer.js

Project description

中文 | English

🐣inquirer_console

An elegant interactive command line interface tool library

InstallationFeaturesUsage ExamplesAPI DocsContributing

Python Version License PRs Welcome

📖 Introduction

inquirer_console is a Python implementation of Inquirer.js, providing a set of well-designed interactive command line interface components that allow developers to easily create beautiful, user-friendly command line applications.

✨ Features

  • Cross-platform compatibility - Perfect support for Windows, macOS, and various Linux/Unix systems
  • Elegant interrupt handling - Intelligent handling of Ctrl+C, ensuring a smooth user experience
  • Powerful input validation - Easily validate user input through custom validate functions
  • Flexible data transformation - Transform user input in real-time through filter functions
  • Chainable API - Provides a fluent API similar to Inquirer.js, simplifying complex interactions
  • Fully type-annotated - Comprehensive type hints to enhance development experience
  • Zero external dependencies - Implemented with pure Python standard library, no additional installations required

🧩 Prompt Types

inquirer_console currently implements the following prompt types:

Type Description Preview
Input Text input prompt > Please enter your name:
Confirm Confirmation prompt (yes/no) > Continue? (Y/n):
Radio Radio prompt (single choice) > Select an option: ❯ Option1 ⬡ Option2 ⬡ Option3
Checkbox Checkbox prompt (multiple choice) > Select multiple options: ❯ [X] Option1 [ ] Option2 [X] Option3
Password Password input prompt > Please enter a password: ******
Text Multi-line text input prompt > Please enter a description: (Press Enter twice to finish)

🚀 Installation

Currently in development stage, you can install it via:

# Install from PyPI
pip install inquirer_console

# Install directly from GitHub
pip install git+https://github.com/Eusen/inquirer_console.git

# Or clone the repository and use
git clone https://github.com/Eusen/inquirer_console.git
cd inquirer_console
pip install -e .

📝 Usage Examples

Using Each Prompt Type Individually

from inquirer_console import Input, Confirm, Radio, Checkbox, Password, Text

# Input prompt
name = Input(
    message="What is your name",
    validate=lambda val: True if val else "Name cannot be empty!"
).prompt()

# Confirm prompt
likes_python = Confirm(
    message="Do you like Python",
    default=True
).prompt()

# Radio prompt
favorite_lang = Radio(
    message="What is your favorite programming language",
    choices=[
        {'name': 'Python', 'value': 'python'},
        {'name': 'JavaScript', 'value': 'js'},
        {'name': 'Rust', 'value': 'rust'}
    ]
).prompt()

# Checkbox prompt
languages = Checkbox(
    message="Which programming languages do you use",
    choices=[
        {'name': 'Python', 'value': 'python', 'checked': True},
        {'name': 'JavaScript', 'value': 'js'},
        {'name': 'Rust', 'value': 'rust'}
    ]
).prompt()

# Password prompt
password = Password(
    message="Please enter a password",
    validate=lambda val: True if len(val) >= 6 else "Password must be at least 6 characters!"
).prompt()

# Multi-line text prompt (finish by pressing Enter twice)
description = Text(
    message="Please enter a project description"
).prompt()

Using inquirer Chain Calls

from inquirer_console import inquirer

# Define a select of questions
questions = [
    {
        'type': 'input',
        'name': 'name',
        'message': 'What is your name',
        'validate': lambda val: True if val else "Name cannot be empty!"
    },
    {
        'type': 'confirm',
        'name': 'likes_python',
        'message': 'Do you like Python',
        'default': True
    },
    {
        'type': 'radio',
        'name': 'favorite_lang',
        'message': 'What is your favorite programming language',
        'choices': [
            {'name': 'Python', 'value': 'python'},
            {'name': 'JavaScript', 'value': 'js'},
            {'name': 'Rust', 'value': 'rust'}
        ]
    },
    {
        'type': 'text',
        'name': 'bio',
        'message': 'Please enter your bio',
        'help_text': 'Press Enter twice to finish input'
    }
]

# Execute the prompt chain
answers = inquirer.prompt(questions)

print(f"Hello, {answers['name']}!")
if answers['likes_python']:
    print("Great, I like Python too!")
print(f"Your favorite language is: {answers['favorite_lang']}")
print(f"Your bio:\n{answers['bio']}")

Gracefully Handling Interruptions

from inquirer_console import inquirer, ExitPromptError

try:
    answers = inquirer.prompt([
        {
            'type': 'input',
            'name': 'name',
            'message': 'What is your name'
        }
    ])
    print(f"Hello, {answers['name']}!")
except ExitPromptError:
    print("\nUser canceled the operation, gracefully exiting...")

🔧 Advanced Usage

Validation and Filtering

from inquirer_console import Input

def validate_age(val):
    try:
        age = int(val)
        if age <= 0:
            return "Age must be a positive integer!"
        elif age > 120:
            return "Age cannot exceed 120 years!"
        return True
    except ValueError:
        return "Please enter a valid number!"

def filter_age(val):
    try:
        return int(val)
    except ValueError:
        return val

age = Input(
    message="What is your age",
    validate=validate_age,
    filter=filter_age
).prompt()

print(f"Your age is: {age} (type: {type(age).__name__})")

Multi-line Text Input

from inquirer_console import Text

# Basic usage - finish by pressing Enter twice
description = Text(
    message="Please enter a project description"
).prompt()

# Supports both double Enter and END text to finish
bio = Text(
    message="Please enter your bio",
    end_text="END"  # Besides double Enter, can also finish by typing END
).prompt()

# Multi-line text input with validation
def validate_code(code):
    if "def main" not in code:
        return "Code must include a main function!"
    return True

code = Text(
    message="Please enter a Python code example",
    help_text="Press Enter twice to finish input (code must include main function)",
    validate=validate_code
).prompt()

📚 API Documentation

For detailed API documentation, please visit our official documentation website.

Basic Prompt Properties

All prompt types inherit from BasePrompt and support the following common parameters:

Parameter Type Description
message str The prompt message displayed to the user
name str The name of the prompt, used to store the answer in the answers dictionary
default Any Default value, used when the user doesn't provide input
validate Callable Validation function, returns True or an error message
filter Callable Filter function, used to process/transform user input

For specific parameters for each prompt type, please refer to the complete documentation.

🧪 Testing

Running Tests

The project uses pytest for testing. To run tests, execute the following commands:

# Run all tests
pytest

# Run a specific test file
pytest tests/test_input.py

# Run a specific test case
pytest tests/test_input.py::test_input_validation

# Run with verbose output
pytest -v

# Generate coverage report
pytest --cov=packages

Adding New Tests

When adding new features, please also add corresponding tests. Test files should be placed in the tests/ directory and should start with test_.

# tests/test_example.py
def test_new_feature():
    # Prepare test data
    # Execute the feature being tested
    # Verify the results meet expectations
    assert result == expected

Test Coverage Goals

Our goal is to maintain at least 90% test coverage. Before submitting a PR, please ensure your code changes have adequate test coverage.

🤝 Contributing

We welcome all forms of contributions, whether they are new features, documentation improvements, or bug fixes. Please check our contribution guidelines to learn how to participate in the project.

Development Environment Setup

# Clone the repository
git clone https://github.com/Eusen/inquirer_console.git
cd inquirer_console

# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate  # Unix/macOS
# or
venv\Scripts\activate  # Windows

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

📄 License

This project is licensed under the MIT License.

💖 Support the Project

If you like this project, you can support us by:

  • ⭐ Starring us on GitHub
  • 📣 Sharing the project on social media
  • 🐛 Submitting issues or PRs
  • 📝 Improving documentation

Made with ❤️

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

inquirer_console-1.1.0.tar.gz (48.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

inquirer_console-1.1.0-py3-none-any.whl (22.6 kB view details)

Uploaded Python 3

File details

Details for the file inquirer_console-1.1.0.tar.gz.

File metadata

  • Download URL: inquirer_console-1.1.0.tar.gz
  • Upload date:
  • Size: 48.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for inquirer_console-1.1.0.tar.gz
Algorithm Hash digest
SHA256 dfe69c4c7c0827b912c277070afd24eca83f185137520cffbba8ed22f0f152b3
MD5 e8a6c7067c60b172e4928156d0275a37
BLAKE2b-256 b4fe3bae20f34aa8c318455ea7fc55e819722207fb7caa5977124ebbbd40910f

See more details on using hashes here.

Provenance

The following attestation bundles were made for inquirer_console-1.1.0.tar.gz:

Publisher: publish.yml on Eusen/inquirer_console

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file inquirer_console-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for inquirer_console-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9b29d00ac169069e3c2d65e26c5d876f7ef4f036a8d81155660f502f9952da0e
MD5 4f4c146494d70022f149c4c203b765a8
BLAKE2b-256 a874a626de6a3c4e37308557c6860e119bebc2de9af08e37605fae025a8a4042

See more details on using hashes here.

Provenance

The following attestation bundles were made for inquirer_console-1.1.0-py3-none-any.whl:

Publisher: publish.yml on Eusen/inquirer_console

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page