Giving required inputs to a Python file at different time using a PHP file

Viewed 20

I am going to connect two scripts, one of which is a python file and the other a PHP file. Let's say the python file looks like such as what follows:

python_file.py
first_input = input("First input: ")
second_input = input("Second input: ")

By running python3 python_file.py through the command prompt, there would be something like:

First input: 1
Second input: 2

But the thing is, I want to read the inputs' text, i.e., "First input: " and "Second input: ", through a PHP script and answer to these inputs proportionally.

One can simply use system("python3 python_file.py '1' '2'"); but that's not what I'm looking for. The thing is, I am going to send input 1 first, and after that, the PHP file is terminated, send the second input, which is 2. Note that it is not known when precisely the second input will be sent. So, some functions such as sleep won't be helpful. Is this possible? If so, how can I do this?

Any help is sincerely appreciated.

1 Answers

I think that specific way is not possible:

# write.py
print ("hello")

# read.py
print(input())
print(input())

Because we reach the end of file when the script is over:

$ python write.py | python read.py 
hello
Traceback (most recent call last):
  File "E:\dev\stackoverflow\python\inputs\read.py", line 2, in <module>
    print(input())
EOFError: EOF when reading a line

But we can use subprocess to create processes and check their output from our python scripts:

# advanced_reader.py
import subprocess

byte_output1 = subprocess.check_output(["python", "write.py"])
output1 = str(byte_output1, "utf8")
output2 = input("Second input: ")

print(output1)
print(output2)

Which evaluates to

$ python advanced_reader.py 
Second input: world
hello

world

So you'd just need to replace ["python", "write.py"] with the command and arguments needed to run your PHP script.

(Additionally, you may want to replace some of those excessive newlines, depending on your objective)

Related