简体   繁体   English

使用多线程从 PHP 调用 Python 脚本

[英]Calling a Python script from PHP using Multi-threading

I'm using PHP to display the Python output in the browser.我正在使用 PHP 在浏览器中显示 Python 输出。 Since the Python script takes a long time to print the output, The User Interface gets hung till the Python script finishes its execution.由于 Python 脚本需要很长时间来打印输出,因此用户界面会挂起,直到 Python 脚本完成执行。

Pthreads for Windows is enabled in PHP for multithreading the shell_exec( ) function which invokes the Python script. Pthreads for Windows 在 PHP 中启用,用于多线程调用 Python 脚本的shell_exec()函数。 Inspite of using Pthreads, the User Interface still gets hung.尽管使用了 Pthreads,用户界面仍然挂起。

Here is the code:这是代码:

$output_customer_churn_prediction = "";

class WorkerThreads extends Thread {
    private $workerId;

    public function __construct($id)
    {
        $this->workerId = $id;
    }

    public function run()
    {
        sleep(rand(0, 3));
        echo "Worker {$this->workerId} ran" . PHP_EOL;
        $output_customer_churn_prediction = shell_exec('python '.$_SERVER['DOCUMENT_ROOT'].'/analytics/python/neural-net-prediction-customer-attrition.py');
        print_r($output_customer_churn_prediction);
    }
}

$workers[0] = new WorkerThreads(0);
$workers[0]->start();

print_r($output_customer_churn_prediction, true); 

Even with multithreading, the User Interface (generated by PHP) gets hung while invoking the Python Neural Net script.即使使用多线程,用户界面(由 PHP 生成)在调用 Python 神经网络脚本时也会挂起。

What could be the reason ?可能是什么原因?

PHP is caching the Output. PHP 正在缓存输出。 You Need to deactivate the Output cache.您需要停用输出缓存。 Then your Browser will not hang.那么您的浏览器将不会挂起。

See ob_flush()见 ob_flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM