0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer. I edited my question, as you can see. Can I do string compare of one line in log?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.