pythoninphp

PythonInPHP Banner

Latest Stable Version Total Downloads Build Status License PHP Version Laravel Version


🌟 What is PythonInPHP?

PythonInPHP is a modern, lightweight Laravel integration wrapper that allows you to execute Python scripts securely and seamlessly from within your PHP applications.

Rather than deploying complex microservices, using HTTP APIs, or running raw execution commands prone to security risks, PythonInPHP provides:


✨ Features


📦 Installation

Install the package via Composer:

composer require rakshitbharat/pythoninphp

Laravel’s package auto-discovery will automatically register the PythonServiceProvider and the Python facade.


⚙️ Configuration

Publish the configuration file:

php artisan vendor:publish --tag="pythoninphp-config"

This will create a config/pythoninphp.php file:

return [
    // Define the path to your Python executable
    'executable' => env('PYTHON_EXECUTABLE', 'python3'),

    // Default execution timeout in seconds (null for no timeout)
    'timeout' => env('PYTHON_TIMEOUT', 60),
];

🚀 Usage

Simple Run

Run a Python script relative to your Laravel application’s root directory (base_path()):

use Rakshitbharat\Pythoninphp\Facades\Python;

$output = Python::run('app/Scripts/hello.py');
echo $output; // Prints standard output

Passing Arguments

Arguments passed as an array are securely escaped:

$output = Python::run('app/Scripts/process.py', [
    '--file=data.csv',
    '--verbose'
]);

Error Handling

Script failures (non-zero exit codes) or execution timeouts throw a PythonExecutionException:

use Rakshitbharat\Pythoninphp\Exceptions\PythonExecutionException;

try {
    $output = Python::run('app/Scripts/unreliable.py');
} catch (PythonExecutionException $e) {
    Log::error("Python script failed: " . $e->getMessage());
}

🧪 Local Testing

You can run the PHPUnit test suite locally within a clean, containerized PHP 8.2 environment using Docker:

# 1. Build and install dependencies
docker compose run --rm test-runner composer install

# 2. Run the tests
docker compose run --rm test-runner vendor/bin/phpunit

📄 License

The MIT License (MIT). Please see LICENSE.md for more information.