Run Python Script in Laravel

  1031 views   6 months ago Laravel

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/script.py']);
$process->run();

// 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/script.py', $arg]);

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

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

Or

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

I hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]