php Laravel:致命的Python错误:_Py_哈希随机化_初始化:无法获取随机数以初始化Python Python运行时状态:预初始化

ygya80vv  于 2023-03-11  发布在  PHP
关注(0)|答案(2)|浏览(296)

我可以尝试在Laravel中运行Python脚本。我使用composer require symfony/process来执行此操作。实际上,我不想使用shell_exec()。当我尝试运行它时,返回错误。在命令行中,一切正常。我的Python脚本位于公共文件夹中。

我的控制器:

use Symfony\Component\Process\Process;
    use Symfony\Component\Process\Exception\ProcessFailedException;

    public function plagiarismCheck() {
        $process = new Process(['C:/Program Files/Python39/python.exe', 'C:/Users/User/Desktop/www/abyss-hub/public/helloads.py']);
        $process->run();

        // executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }
        return $process->getOutput(); 
    }

Python脚本:

print('Hello Python')

错误:

The command ""C:/Program Files/Python39/python.exe" "C:/Users/User/Desktop/www/abyss-hub/public/helloads.py"" failed. 
Exit Code: 1(General error) 
Working directory: 
C:\Users\User\Desktop\www\abyss-hub\public 
Output: ================ Error
Output: ================ Fatal 
Python error: 
_Py_HashRandomization_Init: failed to get random numbers to initialize Python 
Python runtime state: preinitialized.
jw5wzhpr

jw5wzhpr1#

使用Symfony进程。https://symfony.com/doc/current/components/process.html安装:

composer require symfony/process

代码:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process(['python', '/path/to/your_script.py']);
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
5vf7fwbs

5vf7fwbs2#

您需要配置进程环境变量:

https://symfony.com/doc/current/components/process.html#setting-environment-variables-for-processes

$process = new Process(["python", $pathToFilePython, ...$yourArgs], env: [
  'SYSTEMROOT' => getenv('SYSTEMROOT'),
  'PATH' => getenv("PATH")
]);

$process->run();
$process->getOutput();
  • PATH:识别“python“命令。
  • SYSTEMROOT:Python工作的操作系统依赖项。

相关问题