如何优雅的在php中调用python程序

需求:通过form表单把值传到python程序中,并把制行结果返回给前端
20201216130139463

听到这个你肯定会想,需求中根本就没有用到php,那为什么还要用php呢,原因是当前主流的后端语言是java和php,虽然python也有web框架如Django,当然如果你会django的话肯定就不会搜索这个问题了。

exec

PHP中有一个函数可以运行第三方的脚本:exec(),来看看exec的函数结构:

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

参数解释(来自PHP手册)

command

要执行的命令。

output

如果提供了 output 参数, 那么会用命令执行的输出填充此数组, 每行输出填充数组中的一个元素。 数组中的数据不包含行尾的空白字符,例如 \n 字符。 请注意,如果数组中已经包含了部分元素, exec() 函数会在数组末尾追加内容。如果你不想在数组末尾进行追加, 请在传入 exec() 函数之前 对数组使用 unset() 函数进行重置。

return_var

如果同时提供 output 和 return_var 参数, 命令执行后的返回状态会被写入到此变量。

返回值:

命令执行结果的最后一行内容。 如果你需要获取未经处理的全部输出数据, 请使用 passthru() 函数。

如果想要获取命令的输出内容, 请确保使用 output 参数。

PHP带参数制行python程序

只需要在python.py文件后面空格加上参数即可:

1
2
3
4
exec("python test.py {$underGraduate} 
{$achievement} {$language} {$GREGMAT}
{$Recommender} {$background}
{$postGraduate}" ,$outputs);

python接收参数

1
2
3
import sys
for data in sys.argv:
print(data + 'dangdang')

在python中我们把接收到的参数后面加个dangdang,再传回去验证一下是否已经被python修改。

案例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
if (isset($_POST['dosub'])){
$underGraduate = $_POST['underGraduate'];
$achievement = $_POST['achievement'];
$language = $_POST['language'];
$GREGMAT = $_POST['GREGMAT'];
$Recommender = $_POST['Recommender'];
$background = $_POST['background'];
$postGraduate = $_POST['postGraduate'];

$cmd="python test.py";
unset($outputs);
exec("python test.py {$underGraduate} {$achievement} {$language} {$GREGMAT} {$Recommender} {$background} {$postGraduate}" ,$outputs);
unset($outputs[0]);
foreach($outputs as $out){
echo $out."<br>";
}
}
?>
<form action="" method="post">
<input type="text" name="underGraduate">
<input type="text" name="achievement">
<input type="text" name="language">
<input type="text" name="GREGMAT">
<input type="text" name="Recommender">
<input type="text" name="background">
<input type="text" name="postGraduate">
<input type="submit" name="dosub">
</form>

执行结果

都传一个111的参数:
20201216130500846
提交后:
20201216130532487
可以看到php打印出来的值已经发生了变化,所以成功执行了py程序!