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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题