makiTurbo
makiTurbo

Reputation: 99

Interact with running python script with PHP

I have python script which may can ask for input while running (I must run it from PHP and can't modify python script). My question is, can I interact with that script with PHP. For example, run "python script.py" and then if last message is "String:", than insert input.

>> python script.py
>> Log 1 ...
>> Log 2 ...
>> Enter value A:
>> 2
>> Enter value B:
>> 4

i want to do this.

If(cmdlogtext == 'Enter value A:')
* Enter number 2

Upvotes: 0

Views: 456

Answers (2)

Lessmore
Lessmore

Reputation: 1091

To interact with running script you need to use proc_open.

proc_open Official docs

Below example is a simple usage.

$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("file", "error-output.txt", "a") // stderr is a file to write to
);

$process        = proc_open('python script.py', $descriptorspec, $pipes);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to error-output.txt


    fwrite($pipes[0], 'Input 1' . PHP_EOL);
    fwrite($pipes[0], 'Input 2' . PHP_EOL);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[0]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);
}

Keep in mind:
To send inputs to running script, you must use fwrite on $pipes[0].
All parameters needs to be ended by PHP_EOL

Upvotes: 1

Sina
Sina

Reputation: 369

You can use the exec function and then inspect the output.

exec("python script.py", $output, $returnValue);

Edit: Re-read your question and I'm not sure about interactively providing input but you may be able to modify the exec() function to pass arguments to the Python script assuming the script can accept them.

Upvotes: 0

Related Questions