duanhuchang5056
2015-10-02 13:20
浏览 112

运行python文件并读取输出

I'm trying to run python file from PHP

What I'm looking for is :

1- run python file from index.php

2- read the output of python file and show it in index.php

Example :

# 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

And in index.php should be some thing this :

<?php
$read = exec("python test.py user@dmoain.tld 123456");

if($read == "ok, registerd")
    {
        echo "succesful registerd";
    }
else ($read == "I can\'t")
    {
        echo "failed";
    }

?>

I'm not sure what should I do in index.php how can I do it?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从PHP运行python文件

我是什么 我要找的是:

从index.php运行python文件

2-读取python文件的输出并在索引中显示它。 php

示例:

 #test.py 
 
 
import sys 
 
user = sys.argv [1]  
password = sys.argv [2] 
 
def read():
 if user ==“user@dmoain.tld”and password ==“123456”:
返回“ok,registerd”
 else: 返回“我不能”
try:read()
except:pass 
   
 
 

在index.php中应该是这样的:

 &lt;?php 
 $ read = exec(“python test.py user@dmoain.tld 123456”); 
 
if($ read ==“ok,registerd”)  
 {
 echo“成功注册”; 
} 
else($ read ==“我不能”)
 {
 echo“failed”; 
} 
 
?&gt; \  n   
 
 

我不知道我应该怎么做index.php怎么办呢?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doucitan2544 2015-10-02 13:35
    已采纳

    First, your last else is wrong on the php script,

    instead of:

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

    use:

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

    Your python script was not working either. I didn't debug it, simply wrote a new one that works.

    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";
        }
    ?>
    
    点赞 打赏 评论

相关推荐 更多相似问题