RafaelM
RafaelM

Reputation: 128

Execute Python script using Laravel?

I'm trying to execute a python script in a Laravel 5.8 project but I'm having problems with the Symfony/process class.

Basically, I want to run this python script that takes an excel form from the storage folder.

My first try was this

$process = new Process('C:\Python\python.exe C:\Users\"my path"\laravel\storage\app\images\cargaExcel.py');

$process->run();

if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

And the error is

Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers to initialize Python

I also tried with shell_exec(), and if the two files (the excel and the python script are in the public path - app/public) it works.

I think the problem is that python only executes on the app/public folder, so I don't know how to run this in another path.

Python output is telling me that:

Working directory: C:\Users\"my path"\laravel\public

Does anyone know how to run this?

Upvotes: 7

Views: 1393

Answers (1)

Riccardo Venturini
Riccardo Venturini

Reputation: 478

You can pass the working directory as the second argument of the process class

So it can be:

$process = new Process('C:\Python\python.exe C:\Users\"my path"\laravel\storage\app\images\cargaExcel.py', "/my/working/path/");

Also you may pass command as array

$process = new Process(['C:\Python\python.exe', 'C:\Users\"my path"\laravel\storage\app\images\cargaExcel.py'], "/my/working/path/");

Upvotes: 1

Related Questions