0

So my directory structure is like this:

parent_folder
    my_project
        __init__.py
        __main__.py
        models
            __init__.py
            a_model.py
        controllers 
            __init__.py
            a_controller.py
        utilities
            __init__.py
            a_utility.py

The way I'm executing my_project right now, is by launching a terminal in parent_folder and then executing the following command:

python -m my_project

This works fine. However, I wish to execute this from within a PHP script:

<?php
$output=shell_exec('python /path/to/parent_folder -m my_project');
echo "<pre>$output</pre>";
?>

Though, it's not working. Being new to python, I am just wondering what is the way to do this?

2
  • What do you mean by "not working" - do you get an error message? Commented Nov 18, 2018 at 15:34
  • Well, the output from the python should be displayed. But nothing is displayed, so my guess is that that the way I'm calling my python stuff is incorrect Commented Nov 18, 2018 at 15:36

1 Answer 1

1

If you check your error log, you'll probably see a message saying can't find '__main__' module in /path/to/parent_folder. You have to add "2>&1" to the command to make shell_exec return error output.

To replicate your way of running the project, you should change to the module directory with cd and then run python:

<?php
$output=shell_exec('cd /path/to/parent_folder && python -m my_project 2>&1');
echo "<pre>$output</pre>";
?>

An alternative is adding the path to your module to PYTHONPATH, which python -m uses when it searches for modules. You can do this in PHP before calling the shell, or globally on your system. In PHP it would be:

<?php
putenv("PYTHONPATH=/path/to/parent_folder");
shell_exec('python -m my_project 2>&1');
echo "<pre>$output</pre>";
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, exactly what i was looking for!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.