# Python URL Shortener

This utility shortens long URLs using the `pyshorteners` library, which supports various URL shortening services (like TinyURL, Is.gd, etc.) via a simple API.

**Modules Used:**
*   `pyshorteners`: To interact with URL shortening APIs.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.

## Installation

```bash
pip install pyshorteners
```

## The Code

Save this as `shortener.py`.

```python
import pyshorteners
import argparse
import sys

def shorten_url(url, service='tinyurl'):
    try:
        # Initialize the shortener
        s = pyshorteners.Shortener()
        
        print(f"Shortening {url} using {service}...")
        
        # Select service
        # Note: Some services like bitly require API keys to be passed to the constructor
        if service == 'tinyurl':
            short_url = s.tinyurl.short(url)
        elif service == 'clckru':
            short_url = s.clckru.short(url)
        elif service == 'dagd':
            short_url = s.dagd.short(url)
        elif service == 'isgd':
            short_url = s.isgd.short(url)
        else:
            print(f"Error: Service '{service}' not supported in this script.")
            return

        print(f"Short URL: {short_url}")
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="URL Shortener CLI")
    parser.add_argument("url", help="The URL to shorten")
    parser.add_argument("--service", default="tinyurl", 
                        choices=['tinyurl', 'clckru', 'dagd', 'isgd'],
                        help="Shortening service to use (default: tinyurl)")
    
    args = parser.parse_args()
    
    shorten_url(args.url, args.service)
```

## Usage

```bash
# Default (TinyURL)
python shortener.py https://www.google.com/search?q=python+programming

# Use a different service (e.g., Is.gd)
python shortener.py https://www.github.com --service isgd
```

[[programming/python/python]]