简体   繁体   中英

how can I pass the value of html/php page to Python script

I have a very simple question ... I have a two input text field and a output text field in php page (index.php) and a multiply function code in Python (add.py). Now I want to take the input from php page and calulate the result within python funtion and print the result on php output text field. I do not have any idea how to do it.

index.php

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
    Input 1: <input type="text" name="number" value="<?php echo $input1;?>">
    <span class="error">* <?php echo $inputErr;?></span>
    <br>
    <br>
    Input 2: <input type="text" name="number" value="<?php echo $email;?>">
    <span class="error">* <?php echo $inputErr;?></span>
    <br>
    <br>
    Output:
    <textarea name="output" rows="5" cols="40">
        <?php echo $output;?>
    </textarea>
    <br>
    <br>

    <input type="submit" name="submit" value="Submit">  
</form>

multiply.py

number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
mul = number1 * number2
print("Multiplication of given two numbers is: ", mul)

First you'll have to change your python script so it can gets numbers from the commandline arguments instead of reading from stdin. You may also want to change the output so it only prints the result without other unrelated text:

# add.py
# NB : this should really be named 'multiply', not 'add'

import sys
try:
    number1 = int(sys.argv[1])
    number2 = int(sys.argv[2])
except (IndexError, ValueError):
    sys.exit("usage: python add.py <number1> <number2>")

result = number1 * number2
print(result)

Then on the php side it's just a matter of calling the script with exec with the proper command string (you have to insert the numbers in the command string) and reading the result from the $ouput array.

This being said, one can only wonder why you want to call a Python script to do such a simple thing as a multiplication...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM