1

I am currently trying to create a .php file that displays the output of a python file. Here is what I have so far (that semi works).

test.php

<?php

    echo "Results from wordgame.py...";
    echo "</br>";
    $output = exec('python wordgame.py cat dog');
    echo $output;

;?>

Here is what test.php returns...

Results from test.py...
dog

Here is the output from 'wordgame.py cat dog' I get when running it from the command line:

Generated: 2454
Expanded: 83
Revisited: 0
Path:
        dog
        cog
        cag
        cat

My question is, how do I get test.php to print out the same thing it prints at the command line? wordgame.py doesn't "return" anything, it just prints the lines once it's found a path between the words. Any and all help is appreciated!

1 Answer 1

3

Instead of exec, have a look at passthru. This function has no return value, but will echo the entire output of your python script directly to the browser.

echo "Results from wordgame.py...<br/>";
passthru('python wordgame.py cat dog');

Because you have <br/> in your original post, you may need to escape the python output and wrap it in a <pre/> tag to get the output formatted well for the browser. The easiest way to do this would be with php output buffering.

echo "Results from wordgame.py...<br/>";
ob_start();
passthru('python wordgame.py cat dog');
echo "<pre>" . htmlspecialchars(ob_get_clean()) . "</pre>";

This will work as long as wordgame has relatively short output. If not, you'll need to use a more elaborate solution involving proc_open on the PHP side, or make sure your python code is outputting escaped HTML.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this resource. I have replaced exec with passthru and it works! I will accept this as the answer shortly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.