How to input data from a web page to Python script most efficiently

14,378

Solution 1

I now managed it with the exec() command.

<html>
<body>

<form action="test.php" method="get">
<input type="text" name="name" />
<input type="submit" />
</form>

</body>
</html> 

test.php:

<?php
exec("python mypythonscript.py ".$name, $output);
?>

Solution 2

To get a value from the form you could change action="test.php" to action="/where_you_hooked_your_webapp".

The code of the application could be:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def handle_input():
    userIn = request.args.get('name', 'default name goes here')
    # grab data from the web, prepare data for html template, etc
    return render_template('user.html', user=userIn, data=data)

To find out how you can deploy it see Flask Quickstart e.g., Apache with mod_wsgi.

Share:
14,378
birgit
Author by

birgit

Freestyle coder, part-time hacker, nutcracker

Updated on June 17, 2022

Comments

  • birgit
    birgit almost 2 years

    How can I most easily input data from a web page and pass it to a Python script?

    I've been reading here and on other forums a lot about Python in connection with php or cgi, or even Tornado, Django, etc but I am quite puzzled what is the best solution for me.

    I have a Python script that grabs data from the web, generates .html pages etc - when being run there is just one

    userIn=str(raw_input())
    

    which makes the script gather data based on the input in the terminal. I now only want this input to be coming from some sort of

    <html>
    <body>
    
    <form action="test.php" method="get">
    Name <input type="text" name="name" />
    <input type="submit" />
    </form>
    
    </body>
    </html> 
    

    In the file test.php I have tried passing the value in any kind (proc_open, exec...) but I do not seem to get the connection between python and this form, on top of that I am not sure what's the best idea to pass python's output (some debugging-errors etc) back to the web-interface?!

    Thanks a lot!