7

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?

jww
  • 97,681
  • 90
  • 411
  • 885
RafaelM
  • 128
  • 9
  • Check this https://stackoverflow.com/questions/41020068/running-python-script-in-laravel – Prafulla Kumar Sahu Mar 15 '19 at 12:59
  • how about `$cwd = getcwd(); chdir(new wordking direcotry); run python; chdir($cwd)` ? – apokryfos Mar 15 '19 at 13:49
  • @apokryfos thanks, that's the way to solve. – RafaelM Mar 26 '19 at 16:44
  • 1
    Possible duplicate of [Running python script in Laravel](https://stackoverflow.com/q/41020068/608639), [How to run Python Script in Laravel?](https://stackoverflow.com/q/38724318/608639), etc. – jww Jul 22 '19 at 17:02
  • create a virtual environment venv of python & run that python file path in virtual env from instance of process class – bhucho Feb 05 '21 at 16:47

1 Answers1

1

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/");