2

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 == "[email protected]" 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 [email protected] 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?

3
  • Hint: you might want to replace try: read() with with try print read() ... this will cause your python program to output the return value to stdout, which I think php's exec will then return to your $read variable. If that's not the issue, you should identify what's happening or not happening Commented Oct 2, 2015 at 13:28
  • else should be elseif. Enable error reporting. Commented Oct 2, 2015 at 13:29
  • Also except: pass is, generally speaking, a very bad idea. Commented Oct 2, 2015 at 13:51

2 Answers 2

6

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 == "[email protected]" and password == "123456":
    print  "OK"
else: 
    print  "KO"

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 [email protected] 123456");
if($read == "OK")
    {
        echo "ok, registered";
    }
else if($read == "KO")
    {
        echo "failed";
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

0

try 'system' instead of '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;
?>

see php manual

1 Comment

Can you explain why? are there performance differences? or maybe security issues with exec() ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.