# taskkill

Cross-platform process termination utility for Windows and Unix-like systems.

## Overview

The `taskkill` module provides a unified interface for terminating processes across different operating systems. It supports pattern matching, process caching for performance, and safety mechanisms to prevent accidental mass termination.

## Features

- **Cross-platform support**: Works on both Windows (using `taskkill`) and Unix-like systems (using `kill`)
- **Smart fuzzy matching**: Automatically performs substring matching when no wildcards are specified (e.g., `taskk python` matches `python.exe` and `python3.exe`)
- **Explicit wildcard support**: Supports traditional wildcard patterns when needed (e.g., `taskk python*` for prefix matching)
- **Process caching**: Caches process list to improve performance for multiple operations
- **Safety thresholds**: Prevents accidental termination of too many processes
- **Force mode**: Allows bypassing safety thresholds when needed
- **Detailed logging**: Comprehensive output for monitoring operations

## Installation

This module is part of the `pytola` package. Install the complete package:

```bash
pip install pytola
```

## Usage

### Command Line Interface

```bash
# Terminate processes containing "notepad" (fuzzy match)
taskk notepad

# Terminate processes starting with "python" (explicit prefix match)
taskk python*

# Terminate processes matching complex pattern
taskk *chrome*tab*

# Enable debug output
taskk chrome --debug

# Force termination (bypass safety threshold)
taskk temp --force

# Terminate multiple processes
taskk firefox chrome edge
```

### Programmatic Usage

```python
from pytola.taskkill.taskkill import kill_process, get_process_list, get_matched_process

# Get current process list
get_process_list()

# Find processes containing "python" (fuzzy match)
matches = get_matched_process("python")
print(f"Found {len(matches)} matching processes")

# Find processes starting with "chrome" (explicit pattern)
matches = get_matched_process("chrome*")

# Terminate processes containing "notepad"
kill_process("notepad")

# Force termination with explicit pattern
kill_process("temp*", force_refresh=True)
```

## API Reference

### Main Functions

#### `kill_process(process_name: str, force_refresh: bool = True) -> None`

Terminate processes matching the given name or pattern.

**Parameters:**

- `process_name`: Process name or pattern to match (supports wildcards)
- `force_refresh`: Whether to refresh the process list (default: True)

#### `get_process_list(force_refresh: bool = False) -> None`

Retrieve the current list of processes.

**Parameters:**

- `force_refresh`: Force refresh even if cache exists (default: False)

#### `get_matched_process(process_name: str) -> list[ProcessInfo]`

Get processes matching the given pattern.

**Parameters:**

- `process_name`: Pattern to match against process names

**Returns:**

- List of matching `ProcessInfo` objects

### Data Classes

#### `ProcessInfo`

Represents information about a process.

**Attributes:**

- `name`: Process name
- `pid`: Process identifier

### Constants

#### `_max_match_threshold`

Maximum number of processes that can be matched without confirmation (default: 10).

## Safety Mechanisms

The module includes several safety features:

1. **Matching threshold**: Limits the number of processes that can be terminated in one operation
2. **Pattern specificity**: Encourages use of specific patterns to avoid accidental matches
3. **Warning system**: Alerts when many processes match a pattern
4. **Force flag**: Requires explicit opt-in for bulk operations

## Performance Considerations

- Process lists are cached to avoid repeated system calls
- Pattern matching uses efficient string operations
- Large process lists are handled gracefully with pagination warnings

## Platform Differences

### Windows

- Uses `tasklist /fo csv /nh` to enumerate processes
- Uses `taskkill /F /PID <pid>` to terminate processes
- Handles both GBK and UTF-8 encoding

### Unix/Linux

- Uses `ps -eo pid,comm --no-headers` to enumerate processes
- Uses `kill -9 <pid>` to terminate processes

## Error Handling

The module provides comprehensive error handling:

- Process enumeration failures are logged and handled gracefully
- Termination failures are reported individually
- Encoding issues are handled with fallback mechanisms
- Permission errors are properly reported

## Testing

Run the test suite:

```bash
# Run unit tests
pytest pytola/taskkill/tests/test_taskkill.py

# Run benchmark tests
pytest pytola/taskkill/tests/test_benchmark.py -m benchmark

# Run all tests
pytest pytola/taskkill/
```

## Examples

### Basic Usage

```python
# Terminate processes containing "notepad" (fuzzy match)
kill_process("notepad")

# Terminate all processes starting with "python"
kill_process("python*")

# Terminate with debug output
import logging
logging.getLogger().setLevel(logging.DEBUG)
kill_process("chrome")
```

### Advanced Usage

```python
# Check what would be affected before terminating
get_process_list()
matches = get_matched_process("temp*")
print(f"Would terminate {len(matches)} processes:")
for process in matches:
    print(f"  {process.name} (PID: {process.pid})")

# Proceed with termination
kill_process("temp*")
```

## Contributing

See the main project documentation for contribution guidelines.

## License

See the main project LICENSE file.
