php - 运行 python 文件并读取输出

标签 php python

我正在尝试从 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/

相关文章:

php - SESSION检查后无法登录

python - opencv 在 python 中运行但在 spyder 中不运行

Python NET 初始化一个锯齿状数组

python lxml.html.parse不读取url

php - 数组-将数组值插入mysql表

php - PHP 中使用 LIKE 和 WHERE 查询进行选择

python - 将 C 或 numpy 数组转换为具有最少副本数的 Tkinter PhotoImage

python - 如何卸载 Anaconda(Mac)

php - 将 MySQL 转换为 Json 结果集

php - 撇号 (') 转换为 �