0

I'm trying to run a python script from Laravel, with Symfony Process component like this :

My controller :

public function access(Request $request)
{
    $process = new Process(['test.py', 'helloworld']);
    $process->run();
    dd($process->getOutput());
}

Python script :

import sys
x = sys.argv[1]
print(x)

But all i get in dd is ""

What do you think is the problem ?

gp_sflover
  • 3,460
  • 5
  • 38
  • 48
Nielson
  • 49
  • 10
  • 1
    Python files are not executable files, unless they have a shebang + execution permission and you run it from a shell. Instead of this, you should add the python interpreter as the 1st array argument, something like this (not tested at all): `new Process(['/usr/bin/python', 'test.py', 'helloworld'])` – yolenoyer Jun 20 '20 at 18:52
  • Same result.. I don't know how i can execute a py script from laravel – Nielson Jun 20 '20 at 19:03
  • Can you try by replacing your python filename with a full path? Something like `new Process(['/usr/bin/python', '/my/full/path/test.py', 'helloworld'])` – yolenoyer Jun 20 '20 at 19:11
  • Still nothing.. – Nielson Jun 20 '20 at 19:24

2 Answers2

0

Not an answer, just a tip but too long to fit as a comment:

Instead of dumping only the standard output, you can dump as well other useful information:

$process = new Process(['/usr/bin/python', '/my/full/path/test.py', 'helloworld']);
$process->run();

echo "Output:\n";
dump($process->getOutput());
echo "Error:\n";
dump($process->getErrorOutput());
echo "Exit code: " . $process->getExitCode() . "\n";
die;
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
  • Thank you i got this as the ErrorOutPut : """ Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers to initialize Python Python runtime state: preinitialized """ – Nielson Jun 20 '20 at 19:39
  • Hitting the same issue. Might be because my build environment is Windows. I also read this: https://www.scivision.dev/python-calling-python-subprocess/ but I've not figured out a solution. Did you ever resolve? – scottsuhy Nov 11 '20 at 16:29
0

Symfony process keeps throwing Fatal Python error: _Py_HashRandomization_Init error, used shell_exec() instead.

 <?php
    $var = "Hello World";
    $command = escapeshellcmd('path_to_python_script.py '.$var);
    $output = shell_exec($command);
    echo $output;
 ?>

you can also send file instead of variable and have it handled from python. if you want to get runtime inputs checkout Brython or Skulpt.

fasameer
  • 41
  • 2