簡體   English   中英

使用shell_exec或exec來使用STDIN&STDOUT從命令行通過輸入傳遞來運行python文件

[英]Using STDIN & STDOUT using shell_exec or exec anything else for running a python file from command line wih input passing

我想使用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個,那將是很大的幫助。

終於我找到了解決方案。 最好的方法是使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM