How to Run Python in a Laravel Project
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
This article summarizes how to run Python files within a Laravel project.
Prerequisites
Existing Python Environment Locally
To check if python is installed locally, you can run commands like
python --version
python3 --version
If this command is not available, it means python is not installed in your local environment. Please install it before reading the article.
Explanation of the Process
The timing of running python files may vary, but in this case, we will follow these steps:
- Create the Python file to execute
- Create a php artisan command file
- Write the command to run python
Creating the Python File to Execute
Create app/Python/test.py and write the following code:
print('test')
Creating the Laravel Command File
In Laravel, you can create the command file using the following command (somewhat complicated):
php artisan make:command PythonTestCommand
Make sure that app/Console/Commands/PythonTestCommand.php is created.
Editing PythonTestCommand.php
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
// Other uses are omitted
class PythonTestCommand extends Command
{
protected $signature = 'test:python';
protected $description = 'Test for executing Python files';
// In my environment, the file location is like an argument
$process = new Process(['python', './app/Python/test.py']);
// If you want to know the base directory of the file, running 'pwd' command will give you the base directory.
// $process = new Process(['pwd']);
try {
$process->mustRun();
// \Log::info();
$response = $process->getOutput();
dd($response);
} catch (ProcessFailedException $exception) {
\Log::error($exception->getMessage());
}
}
Result
test
If you see this output, you have successfully run Python!!
While we implemented this with a command, you should be able to use it in Controllers or anywhere else. Give it a try!
Conclusion
That's all for now.
Python has many convenient packages for data and formatting, so consider incorporating it into your Laravel project.
For feedback or complaints, please contact me via Twitter DM.
See you later!
Popular Articles
Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs