2

I cannot get output data from a python script to php. There is no error thrown in the php, and the python script outputs perfectly from the command line. Python:

import json,sys,MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="root", db="sr")
cur = db.cursor()
def requestQuiz():
    sql = "SELECT quiz FROM wordbank ORDER BY RAND() LIMIT 1"
    cur.execute(sql)
    result_set = cur.fetchall()
    quiz = result_set[0][0]
    return json.dumps(quiz)

if __name__ == "__main__":
    #print solve(sys.argv[1])
    print requestQuiz()

PHP

<?php
$result = exec("python request.py");
$results_array = json_decode($result);
echo "<p>".$results_array."</p>";
?>

python should return a single word in quotes, such as "happy" And it does so when I tried it from command line

python request.py

I've confirmed that the php and python are in the same directory and the python script named "request.py"

  • Who is the owner of that file? Is it executeable (`chmod('request.py', '+x')`)? – Xorifelse Jan 27 '17 at 01:31
  • What do you mean you "cannot get output data"? Is the returned data empty? Is an error thrown? – Carcigenicate Jan 27 '17 at 01:31
  • @Carcigenicate There's no error thrown in the PHP. What I mean by "cannot get output data" is that nothing shows up on the webpage, but I inspected HTML, there is

    , yet nothing inside

    .

    – Tiancheng Xu Jan 27 '17 at 02:42
  • Read the docs for PHP's [`exec()`](http://php.net/manual/en/function.exec.php): "Return Values: The last line from the result of the command." It's only getting one line of the Python script output, not the whole JSON document. So json_decode() fails to parse the incomplete JSON, and returns NULL. You need to use `shell_exec()` or `passthru()` to get all the output of the Python script. – Bill Karwin Jan 27 '17 at 02:44
  • @BillKarwin I tried both, doesn't work. Hmm, python should return a single word, and it does so from the command line. Sorry, I'm a newbie here. – Tiancheng Xu Jan 27 '17 at 03:04

1 Answers1

0

Try using shell_exec().Like this..

<?php
$result = shell_exec("python request.py");
$results_array = json_decode($result);
echo "<p>".$results_array."</p>";
?>

For more http://php.net/manual/en/function.shell-exec.php

Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19