duanhuchang5056 2015-10-02 13:20
浏览 167
已采纳

运行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?

  • 写回答

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";
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看