ezgooey

Simplified usage of https://github.com/chriskiehl/Gooey that turns argparse-based Python CLIs into GUI apps

View the Project on GitHub twardoch/ezgooey

ezgooey: Create GUIs for CLI Apps Effortlessly

ezgooey is a Python utility that simplifies the process of adding a Graphical User Interface (GUI) to your command-line interface (CLI) applications built with argparse. It acts as a lightweight wrapper around the powerful Gooey library, allowing your application to run as a GUI when no command-line arguments are provided, and as a standard CLI tool when arguments are present.

Additionally, ezgooey includes a convenient logging module that provides colorful, rich-text-compatible output, enhancing the user experience in both GUI and console modes.

Who is ezgooey for?

ezgooey is for Python developers who:

Why is ezgooey useful?

Installation

You can install ezgooey using pip:

pip install ezgooey

This will also install its dependencies, including Gooey, wxPython, and colored.

How to Use

ezgooey consists of two main components: ezgooey.ez for GUI generation and ezgooey.logging for enhanced logging.

1. ezgooey.ez: Adding a GUI to your CLI

To add a GUI to your argparse-based application, simply import ezgooey and add the @ezgooey decorator to the function where you define your ArgumentParser.

Simple Example:

from argparse import ArgumentParser
from ezgooey.ez import ezgooey # Import the decorator

@ezgooey # Add the decorator here
def create_my_parser():
    parser = ArgumentParser(
        prog='my_app',
        description='This is a demonstration app.'
    )
    parser.add_argument(
        'filename',
        help='Path to the input file',
        widget='FileChooser' # Gooey-specific widget
    )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='Enable verbose output'
    )
    return parser

if __name__ == '__main__':
    parser = create_my_parser()
    args = parser.parse_args()

    if args.verbose:
        print("Verbose mode enabled.")
    print(f"Processing file: {args.filename}")
    # Your application logic here

Explanation:

Advanced Example with Gooey Options:

The @ezgooey decorator can pass various configuration options directly to Gooey.

from argparse import ArgumentParser
from ezgooey.ez import ezgooey

GUI_NAME = 'My Advanced GUI App'
CLI_NAME = 'mycli'

@ezgooey(
    program_name=GUI_NAME,
    default_size=(800, 600),
    navigation='Tabbed', # Example: Use Tabbed navigation
    menu=[{
        'name' : 'Help',
        'items': [{
            'type': 'AboutDialog',
            'menuTitle': 'About',
            'name': GUI_NAME,
            'description': 'An example application using ezgooey.',
            'website': 'https://github.com/twardoch/ezgooey',
            'license': 'MIT'
        }]
    }]
)
def get_advanced_parser():
    parser = ArgumentParser(
        prog=CLI_NAME,
        description='An advanced application with multiple options.'
    )

    group1 = parser.add_argument_group(
        'Input/Output',
        gooey_options={'columns': 1, 'show_border': True}
    )
    group1.add_argument(
        '--input-file',
        widget='FileChooser',
        help='File to process',
        gooey_options={'wildcard': "Text files (*.txt)|*.txt"}
    )
    group1.add_argument(
        '--output-dir',
        widget='DirChooser',
        help='Directory to save results'
    )

    group2 = parser.add_argument_group(
        'Settings',
        gooey_options={'columns': 2}
    )
    group2.add_argument(
        '--iterations',
        type=int,
        default=10,
        help='Number of iterations to run'
    )
    group2.add_argument(
        '--mode',
        choices=['fast', 'slow', 'balanced'],
        default='balanced',
        help='Processing mode'
    )
    return parser

if __name__ == '__main__':
    parser = get_advanced_parser()
    args = parser.parse_args()
    # Your application logic here
    print(f"Input: {getattr(args, 'input_file', 'N/A')}, Output Dir: {getattr(args, 'output_dir', 'N/A')}")
    print(f"Iterations: {args.iterations}, Mode: {args.mode}")

Refer to the Gooey documentation for a detailed list of all available decorator arguments and gooey_options for widgets.

2. ezgooey.logging: Colorful and GUI-Friendly Logging

ezgooey.logging provides a simple way to set up colorful logging that works well in both standard terminals and Gooey’s rich text console display.

Simple Usage:

Initialize the logger once, typically at the start of your application.

# In your main script (e.g., at the beginning)
import ezgooey.logging as logging
logging.init(level=logging.INFO) # Or logging.DEBUG, etc.

# Later in your code (in the same file or others)
import logging # Use the standard logging module
logging.info('This is an info message.')
logging.warning('This is a warning.')
logging.error('This is an error!')
logging.success('Operation completed successfully!') # Custom level

Advanced Usage (Named Loggers):

For more complex applications or libraries, you can use named loggers.

# In your main script (e.g., at the beginning)
import ezgooey.logging as ez_logging # Alias to avoid conflict
ez_logging.init(level=ez_logging.INFO)

# In other modules or parts of your app:
import ezgooey.logging as ez_logging
log = ez_logging.logger('my_module_name') # Get a named logger

log.info('Info message from my_module.')
log.warning('Warning from my_module.')
log.success('Task in my_module succeeded.')

Log Levels:

Besides standard levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), ezgooey.logging adds:

The output is color-coded for severity.

Technical Details

How ezgooey.ez Works

The ezgooey.ez module is designed to be a drop-in enhancement for argparse.

  1. Conditional Import: It attempts to import gooey. If gooey is not installed or if command-line arguments (sys.argv[1:]) are present, ezgooey ensures that the application behaves like a standard CLI tool.
  2. Decorator Logic:
    • If Gooey mode is active (Gooey is available and no CLI args), the @ezgooey decorator uses gooey.Gooey to transform the ArgumentParser function into a GUI. The ArgumentParser used in this case is gooey.GooeyParser.
    • If CLI mode is active, the @ezgooey decorator essentially becomes a pass-through, and the standard argparse.ArgumentParser is used.
  3. Monkey-Patching argparse: To allow you to use Gooey-specific options (like widget or gooey_options) directly within your ArgumentParser’s add_argument, add_argument_group, and add_mutually_exclusive_group calls without breaking CLI mode, ezgooey.ez performs a bit of “monkey-patching.” It wraps these methods of argparse._ActionsContainer. The wrapped versions will simply ignore Gooey-specific keyword arguments if Gooey is not active. This means you can define your parser once with all the Gooey enhancements, and it will work seamlessly in both GUI and CLI environments.

    For example, parser.add_argument(..., widget='FileChooser', gooey_options={...}) will use these options in GUI mode but ignore widget and gooey_options in CLI mode.

How ezgooey.logging Works

The ezgooey.logging module configures the standard Python logging system with a custom formatter and stream handler to provide:

Project Structure

Dependencies

ezgooey relies on the following main libraries:

These are automatically installed when you install ezgooey via pip.

Contributing

Contributions are welcome! If you have suggestions, bug reports, or feature requests, please open an issue on the GitHub repository.

Coding Conventions

Development Setup (Simplified)

  1. Clone the repository.
  2. It’s recommended to work in a virtual environment.
    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. Install dependencies, including development tools:
    pip install -r requirements.txt
    pip install twine wheel # For distribution
    

Building and Distributing

The dist.sh script in the repository is used by the maintainer to create new releases and publish them to PyPI and GitHub. It handles versioning, building wheels/sdist, tagging, and uploading.

For local testing of packaging:

python setup.py sdist bdist_wheel

This will create distribution files in the dist/ directory.

(Note: The project currently does not have an automated test suite. Contributions in this area would be particularly valuable.)

Version History

For a detailed history of changes, please refer to the GitHub Releases page.

License

ezgooey is licensed under the terms of the MIT License. Copyright © 2020-2023 Adam Twardoch.


This README was enhanced with the assistance of an AI coding tool.