运行python文件并读取输出

时间:2015-10-02 13:20:28

标签: 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怎么办呢?

2 个答案:

答案 0 :(得分:3)

首先,您的上一个else在php脚本上是错误的,

而不是:

else ($read == "I can\'t"){

使用:

else if($read == "I can\'t"){

您的python脚本也无法运行。我没有调试它,只是编写了一个有效的新版本。

<强> test.py

import sys

user = sys.argv[1]
password = sys.argv[2]

if user == "user@domain.tld" and password == "123456":
    print  "ok, registered"
else: 
    print  "NOT registered"

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, registered")
    {
        echo "ok, registered";
    }
else if($read == "NOT registered")
    {
        echo "failed";
    }
?>

答案 1 :(得分:0)

尝试使用“系统”而不是“ exec”

    <?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

请参阅php manual