When working on a Laravel application, you may encounter scenarios where Python's robust libraries for data transformation, machine learning, or other complex tasks can complement Laravel's capabilities.
In this article, I’ll walk you through a simple and effective way to execute Python scripts directly from Laravel, providing step-by-step guidance and code snippets. This integration can be a game-changer for applications that need the best of both worlds.
Executing Python Scripts in Laravel A Step-by-Step Guide
Let’s start by creating a Python script that performs a sample task. In this example, the script will accept input, process it, and return the result.
scripts/sample_task.py
import sys
import json
def main():
# Get data from Laravel
input_data = sys.stdin.read()
data = json.loads(input_data)
# Process data (example: multiply input by 2)
result = {"output": data["input"] * 2}
# Return the result
print(json.dumps(result))
if __name__ == "__main__":
main()
In Laravel, we need to create a route and a controller method to execute the Python script.
routes/web.php
use App\Http\Controllers\PythonController;
Route::get('/run-python', [PythonController::class, 'runPythonScript']);
Now, let’s create the controller that handles the execution of the Python script.
app/Http/Controllers/PythonController.php
<?php
namespace App\Http\Controllers;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class PythonController extends Controller
{
public function runPythonScript()
{
// Define the Python script path
$scriptPath = base_path('scripts/sample_task.py');
// Prepare data to send to Python
$inputData = json_encode(['input' => 10]);
// Execute the Python script
$process = new Process(['python3', $scriptPath]);
$process->setInput($inputData);
$process->run();
// Check for errors
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
// Parse Python output
$output = json_decode($process->getOutput(), true);
return response()->json([
'status' => 'success',
'data' => $output,
]);
}
}
The Symfony Process component is used to execute the Python script. Install it using Composer:
composer require symfony/process
Start your Laravel development server:
php artisan serve
Visit the route in your browser or use a tool like Postman:
http://127.0.0.1:8000/run-python
You should receive a JSON response:
{
"status": "success",
"data": {
"output": 20
}
}
You might also like:
In this tutorial we will see how to use scrolla - jQuery plugin for reveal animations when scrolling a mouse. this jquer...
Apr-21-2021
In this example we will see how to upload multiple image in laravel 8. here, we wil see tutorial of multiple image uploa...
Sep-17-2021
In this tutorial, I will let you know how to use summernote editor in laravel, In laravel or PHP many editors are a...
Jun-17-2020
In this post i will show you how to implement bootstrap datetimepicker with example, bootstrap 4 datetimepicke...
Apr-02-2021