Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
python
communitycreator

How to run Python 3 Script in Laravel 7

Chinweuba Elijah Azubuike

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:

  1. The name of the script
  2. 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.

<?php

use 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);
}

RELATED TAGS

laravel
php
python
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring