我正在尝试从 PHP 运行 python 文件
我正在寻找的是:
1- 从 index.php 运行 python 文件
2-读取python文件的输出并在index.php中显示
示例:
# test.py
import sys
user = sys.argv[1]
password = sys.argv[2]
def read():
if user == "user@dmoain.tld" and password == "123456":
return "ok, registerd"
else: return "I can\'t"
try: read()
except: pass
在 index.php 中应该是这样的:
<?php
$read = exec("python test.py user@dmoain.tld 123456");
if($read == "ok, registerd")
{
echo "succesful registerd";
}
else ($read == "I can\'t")
{
echo "failed";
}
?>
我不确定我应该在 index.php 中做什么我该怎么做?
最佳答案
首先,你最后的 else
在 php 脚本上是错误的,
代替:
else ($read == "I can\'t"){
使用:
else if($read == "I can\'t"){
您的 python 脚本也无法正常工作。我没有调试它,只是写了一个新的可以工作的。
测试.py
import sys
user = sys.argv[1]
password = sys.argv[2]
if user == "user@domain.tld" and password == "123456":
print "OK"
else:
print "KO"
index.php
<?php
/*
Error reporting helps you understand what's wrong with your code, remove in production.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
$read = exec("python test.py user@domain.tld 123456");
if($read == "OK")
{
echo "ok, registered";
}
else if($read == "KO")
{
echo "failed";
}
?>
关于php - 运行 python 文件并读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32908112/