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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)