PHP / Python / Bash Emulator - PullRequest
0 голосов
/ 06 ноября 2018

Мне нужно выполнить пользовательский терминал, используя PHP / JS / Python на сервере стека LAMP, чтобы иметь возможность выполнять сценарии. Я могу: сгенерировать команду для выполнения, запустить скрипт и вернуть вывод. Существуют сценарии, которые должны выполняться с непрерывным (бесконечным циклом), которые должны быть уничтожены с помощью kill PID . Тем не менее, мне нужно иметь возможность вызвать вывод из скрипта Python, который работает в фоновом режиме. Пример:

/*** PHP ***/
  <?php
    // AJAX call return
    $data = (object) array();
    $data->command = $_POST['command'];
    exec('python3 ' . $data->command . ' > /dev/null &', $data->output, $data->err);
    die(json_encore($data));
  ?>

/*** HTML ***/
  <HTML>
    <head>
      function submitForm(){
        //... function submits and returns json_object using AJAX
        var data = JSON.parse(__return__);
        var pre = document.createElement("PRE");
        for(var index = 0; index < data.output.length; index++){
          pre.innerHTML += data.output[index] + "<br>";
        }
        document.getElementById("output").append(pre);
      }
    </head>
    <body>
      <div id='output'></div>
      <input type='TEXT' id='command' onchange='submitForm();'/>
    </body>
  </HTML>

/*** PYTHON ***/
  #!/usr/bin/env python3
  import time;
  n = 0;
  while n < 5:
    print("THIS IS THE OUTPUT I NEED TO RETURN TO JSON");
    time.sleep(1);

Issue: Когда я посылаю команду как одну команду, она возвращает вывод; когда я посылаю команду для запуска скрипта, она возвращает ноль; Как я могу вызвать вывод как объект JSON, чтобы получить вывод сценария Python, который запускается из сценария Python выше.

1 Ответ

0 голосов
/ 06 ноября 2018

Для получения полной информации о входе, выходе и ошибках нам нужно использовать функцию proc_open в php. Справочную информацию о функции Php можно найти здесь

<?php

    $data = (object) array();
    $data->command = $_POST['command'];

    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
        1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
        2 => array("pipe", "r")   // stderr is a pipe to read from
    );

    $process = proc_open('python3 ' . $data->command, $descriptorspec, $pipes);
    //It is always a good idea to put full path e.g /usr/bin/python3
    stream_set_blocking($pipes[2], 0); //setting non-blocking on stderr
    fclose($pipes[0]); //closing input

    $data->output = stream_get_contents($pipes[1]); //reading output
    fclose($pipes[1]); //closing output

    $data->err = stream_get_contents($pipes[2]); //reading stderr
    fclose($pipes[2]); //closing stderr

    die(json_encode($data));
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...