0

I set up a php script to run my python package from html page. My python modules call some external proprietary tools via system variables from ~/.bash_profile.

PURPOSE: When I use php to execute my scripts, no environment variables are available (os.getenv() return None).

QUESTION: What is the most efficient method to path system variable from PHP to python?

Thanks in advance

B.Gees
  • 1,125
  • 2
  • 11
  • 28

1 Answers1

1

This function: http://php.net/proc_open has 5th argument named $env to pass any environment variables to the new process.

This is the shortest code I used to run it:

$proc = proc_open(
    "php demo-2.php", // put your python script here
    [
        0 => ['pipe', 'r'],
        1 => ['pipe', 'w'],
        2 => ['pipe', 'a'],
    ],
    $pipes,
    null,
    [
        'SECRET' => $secret,
    ]
);
print stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($proc);

BTW my demo-2.php only contains <?php print_r($_ENV); ?>.

PS. In case you try it with PHP and it only prints empty array, edit your php.ini and set variables_order to contain E, which is responsible for populating $_ENV variable.

ob-ivan
  • 785
  • 1
  • 8
  • 17
  • Thanks a lot for your answer. Python module calls external tools with `os.system()`. I don't know if `proc_open` is able to authorize python to execute this command :/ – B.Gees Feb 02 '18 at 08:06
  • Did you try? What was the result? Sometimes an experiment will tell you more than the theory. – ob-ivan Feb 02 '18 at 09:02
  • I'm newbe in PHP (I've been scripting from only one week for my company). I try to implement that but my python script takes arguments as input. My command line is : `python3.5 /path/to/my/script.py -i filename -p prop1 prop2 -opt True`. I need to replace `php demo-2.php` with my command line ? – B.Gees Feb 02 '18 at 09:10
  • @B.Gees Environment variables and command line arguments are "two big differences", as Odessites say. The difference is neither PHP nor Linux specific, this is how programs are executed in any OS. Please see here for a discussion: https://stackoverflow.com/questions/7443366/argument-passing-strategy-environment-variables-vs-command-line --- If you need to access environment variables with `os.getenv()`, use `$env` parameter to `proc_open` (this is the only way in PHP, afaik). If you only need command line arguments, call `exec('your whole command line here')`. Hope this helps. – ob-ivan Feb 02 '18 at 13:00
  • thanks a lot for your assistance. I'm so sorry, my question is not clear. I update this in a new post. – B.Gees Feb 02 '18 at 13:39