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:
Setting up and configuring Angular 15, the latest version of the popular JavaScript framework, is a crucial step in star...
Jun-07-2023
In this article, we will see how to image upload in CKEditor with laravel 10. Here, we will learn about image uploa...
May-08-2023
This article will show us how to validate upload file type using javascript. Using this post we can easily check the sel...
Aug-03-2020
In this article, we will explore the process of sending emails in Laravel, covering versions 6, 7, 8, 9, and 10. Email f...
Sep-02-2020