简体   繁体   中英

Executing python from within php

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?

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>";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM