Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

Passing variable from PHP button to python script

I've create PHP script that takes in user input and sends it to a Python script. The Python script creates an image which the PHP script displays.

Here's my Python code:

import sys
import matplotlib.pyplot as plt
import numpy as np
import ftplib

result = sys.argv[1]

x = np.arange(0, result, 0.1)
y = np.sin(x)

plt.plot(x, y)
plt.savefig('image.png')

My PHP code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Contact Form</title>
</head>
<body>
    <h2>Value identifier</h2>
    <p>Please fill in the value:</p>
    <form action="" method="post">
        <p>
            <label for="inputName">Name:</label>
            <input type="text" name="value" id="inputName">
        </p>
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>


<?php
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);

    $values=$_POST['value'];
    $rad=exec("python test.py".$values);
    echo $values;
    echo $rad;
    echo "<img src='image.png'>";


?>

I don't get anything published, as if the Python script isn't even running. But printing the values I want to pass is successful.

question from:https://stackoverflow.com/questions/66054688/passing-variable-from-php-button-to-python-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key line:

$rad=exec("python test.py".$values);
``
shouldn't be concatenated.  The period should be a comma.  Also, you don't need python before test.py.  You do need the filepath, however.  Also, you may want to try shell_exec() instead of exec() because that will just return a string, and you can print out the string to see what you are getting.  See below:

$rad = shell_exec('/home/path/path/path/RELATE/main.py')

Separately, this question is similar to the one you are asking and gives you a separate way to get PhP to talk to Python using a text file as an intermediary.  The benefit of this is that it would at least help you identify whether you have a PhP problem or a Python problem when there is a bug in your code.

https://stackoverflow.com/q/47981370/9807545

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...