1

我想使用exec函数从我的 php 代码运行 python 文件。为此,我使用命令"python test.py",如果我打印“Hello World”,它就会显示出来。

为此,我的 php 代码是这样的:

<?php
$Data = exec("python test.py");
echo $Data;
?>

而python代码是:

print("Hello World")

现在我想向文件传递一个输入值,比如我的名字“Razin”。这样它就会打印出来"Hello Razin"

这是我的python代码

x = input()
print ("Hello "+x)

应该打印Hello Razin。从php我抓住了它。

我不想传递参数并python system用来捕捉它。我想让它像代码判断系统一样。

我听说过管道并阅读了它。但这并没有明确我的概念。

注意:如果您还可以描述是否有超过 1 个输入,那么这将是一个很大的帮助。

4

1 回答 1

0

最后我找到了解决方案。最好的方法是使用proc_open()

代码示例如下。

$descriptorspec = array(
                    0 => array("pipe", "r"), //input pipe
                    1 => array("pipe", "w"), //output pipe
                    2 => array("pipe", "w"), //error pipe
                );
 //calling script with max execution time 15 second
$process = proc_open("timeout 15 python3 $FileName", $descriptorspec, $pipes);
if (is_resource($process)) {
   fwrite($pipes[0], "2"); //sending 2 as input value, for multiple inputs use "2\n3" for input 2 & 3 respectively
   fclose($pipes[0]);
   $stderr_ouput = [];
   if (!feof($pipes[2])) {
   // We're acting like passthru would and displaying errors as they come in.
         $error_line = fgets($pipes[2]);
         $stderr_ouput[] = $error_line;
    }

    if (!feof($pipes[1])) {
             $print = fgets($pipes[1]); //getting output of the script
    }
}

proc_close($process);
于 2019-07-23T12:57:54.217 回答