【问题标题】:Sending and receiving data between python and php [duplicate]在python和php之间发送和接收数据[重复]
【发布时间】:2018-04-08 22:28:48
【问题描述】:

我想从 php 文件中的表单向 python 函数发送一个字符串。

接收“字符串参数”的python函数将处理它并将“结果字符串”返回到同一个php文件中并显示它。

请指导我怎么做。

更新 我在 Windows8.1 和 Python3.6.4 上使用 xampp 服务器 我已成功使用 shell_exec() 将参数从 php 发送到 python,但无法将变量从 python 返回到 php。

我的 PHP 代码:(index.php)

$param1 = "abc";
$param2 = "xyz"
shell_exec("python C:/python/echo.py $param1 $param2");

我的 Python 代码 (echo.py)

import sys
x = sys.argv[1]
y = sys.argv[2]
print(x)
print(y)
#here I want to return string
#return "code executed successfully"
# and receive this sentence back in new.php file & display it with proper css

(注意:我已经在 StackOverflow 上阅读了许多类似问题的答案,但找不到特定于该场景的答案)

【问题讨论】:

  • @ObsidianAge 这是一个类似的问题,但不是重复的。我的问题中解释的性质和场景非常不同。如果可以的话请帮忙。谢谢:)
  • @James 我已经更新了问题。

标签: php python


【解决方案1】:

shell_exec 分配给变量($resultAsString) 似乎是我的解决方案。

PHP:

<?php 

  //your variables that you are assigning
    $param1 = 'one';
    $param2 = "two";
  //This is where you pass the variables into Python 
    $command = escapeshellcmd("/python/echo.py $param1 $param2");
  //assign the execution to a variable
    $resultAsString = shell_exec($command);
    echo $resultAsString;
?>

Python:

import sys
ResultAsString = ''

#some computing as an example
for x in sys.argv:
    if (x == sys.argv[0]):
        continue
    else:    
        ResultAsString += str(x)+" "

#everything you print will be returned to PHP as a single string
print(ResultAsString)

【讨论】:

    【解决方案2】:

    shell-exec的手册:

    此函数在发生错误或程序运行时都可以返回 NULL 不产生任何输出。无法检测到执行失败 使用这个功能。访问程序时应使用exec() 退出代码是必需的。

    exec的手册:

    string exec ( string $command [, array &$output [, int &$return_var ]] )
    

    return_var
    如果 return_var 参数与输出参数一起存在, 然后将执行命令的返回状态写入此 变量。

     

    试试这个(未经测试的代码,所以测试一下):

    exec('python C:/python/echo.py',  ['abc', 'xzy'], $return_value);
    

    $return_value 是您正在寻找的。​​p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2019-10-11
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多