How to run Python 3 Script in Laravel 7
Python offers some functionalities that can help improve the usefulness of your applications. Python helps handle functionalities such as checking image blur.
Step 1
Run the composer command to install the package as follows:
composer require symfony / process
Step 2
Get your Python script. In this shot, we assume test.py is the Python 3 script we want to run.
Step 3
In this shot, we’ll use the Process class. Laravel ships with a Process class that enables Laravel to run script.
Example
The code below creates a new instance of the Process class, which takes two parameters:
- The name of the script
- The script itself
The script is then executed with the run() method on the $process.
The $process is checked if it runs successfully. In this shot, we just dump the output with the dd() method.
<?phpuse Symfony\ Component\ Process\ Process;use Symfony\ Component\ Process\ Exception\ ProcessFailedException;public function testPythonScript(){$process = new Process(['python', '/path/to/your_script.py']);$process->run();if (!$process->isSuccessful()) {throw new ProcessFailedException($process);}$data = $process->getOutput();dd($data);}