How to run Python script in Laravel 8

When running huge Laravel project with lacs or records, for processing them you might want to use node.js or Python language. Or you want to use OCR, then you need Python which can process the task easily.

In these cases you create the Python script, but you need to trigger from Laravel application. In this article, we will learn how you can run Python script from Laravel application.

First of all, symfony/process is good way to run command.

Install symfony/process using below composer command.

composer require symfony/process

Then you can use in your controller files.

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process(['python', '/path/to/']);

// error handling
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);

$output_data = $process->getOutput();

If you want to pass parameters to python script, you can it with:

$process = new Process(['python', '/path/to/', $arg]);

In addition to above method, you can use PHP's system() or exec() method.

$output_data = system('python /path/to/');


$output_data = exec('python /path/to/');

I hope you like this article.