duanqinbi9029 2019-05-11 10:21
浏览 103
已采纳

使用STDIN和STDOUT使用shell_exec或exec其他任何东西从命令行运行python文件wih输入传递

I want to run a python file from my php code using exec function. To do so I use command "python test.py" and if I print "Hello World", it is showing.

For this my php code is like this:

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

And the python code is:

print("Hello World")

Now I want to pass an input value say my name "Razin" to the file. So that it will print "Hello Razin".

Here is my python code

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

which should print Hello Razin. And from php I catch it.

I don't want to pass arguments and use python system to catch that. I want to make it like code judge system.

I hear about pipe and I read it. But it didn't clear my concept.

N.B: If you can also describe if there is more than 1 input then it'll be a great help.

  • 写回答

1条回答 默认 最新

  • douhuanchi6586 2019-07-23 12:57
    关注

    Finally I found the solution. The best way to do so is using proc_open()

    The code sample is given below.

    $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
    3" 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算