28

Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?

Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?

I started with Django. But it needs some time for the learning. And I also saw something called CGI scripts. Which option should I use?

2

10 Answers 10

16

You are able to run a Python file using HTML using PHP.

Add a PHP file as index.php:

<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>

Passing the parameter to Python

Create a Python file as test.py:

import sys
input=sys.argv[1]
print(input)

Print the parameter passed by PHP.

2
  • Neat! To support spaces in your argument, try doing this instead: echo shell_exec("python test.py \"Parameter 1\""); Apr 30, 2020 at 2:22
  • 1
    There is a whole lot of context missing here (for example, prerequisites). On some Linux server somewhere? Where? Running locally? On a Linux computer? With both the PHP and Python interpreters installed? Where and with what versions was this tested? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). May 29, 2022 at 16:34
7

It probably would depend on what you want to do. I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn. Here are some resources for it:

However, you may still have to do some configuring to allow it to run the program instead of displaying it.

Here's a tutorial on that: Apache Tutorial: Dynamic Content with CGI

8
  • 1
    Thanks a lot for your reply. I went through the example and it's something similar which i'm looking for. But is there a directory structure I need to follow to keep my files? How can I run files? Please clarify.
    – Ann
    Nov 29, 2016 at 9:54
  • I kept all my CGI programs in a directory (cgi-bin) and configured that directory so that the programs are executed. I'll edit to add a link to the tutorial.
    – abacles
    Nov 29, 2016 at 12:24
  • Thanks a lot. I started running programs in cgi.
    – Ann
    Dec 2, 2016 at 14:17
  • No problem! Good luck!
    – abacles
    Dec 3, 2016 at 3:01
  • 1
    @AndrewAnderson yeah, I think so
    – abacles
    Oct 12, 2021 at 12:54
4

Thanks to WebAssembly and the Pyodide project, it is now possible to run Python in the browser. Check out this tutorial on it.

Update: Pyodide v0.21.0

(async () => { // create anonymous async function to enable await

  var output = document.getElementById("output")
  var code = document.getElementById("code")
  
  output.value = 'Initializing...\n'

  window.pyodide = await loadPyodide({stdout: addToOutput, stderr: addToOutput}) // redirect stdout and stderr to addToOutput
        output.value += 'Ready!\n' 
})()


function addToOutput(s) {
  output.value += `${s}\n`
  output.scrollTop = output.scrollHeight
}

async function evaluatePython() {
  addToOutput(`>>>${code.value}`)

  await pyodide.loadPackagesFromImports(code.value, addToOutput, addToOutput)
  try {
    let result = await pyodide.runPythonAsync(code.value)
    addToOutput(`${result}`)
  }
  catch (e) {
    addToOutput(`${e}`)
  }
  code.value = ''
}
<script src="https://cdn.jsdelivr.net/pyodide/v0.21.3/full/pyodide.js"></script>

Output:
<textarea id="output" style="width: 100%;" rows="10" disabled=""></textarea>
<textarea id="code" rows="3">import numpy as np
np.ones((10,))
</textarea>
<button id="run" onclick="evaluatePython()">Run</button>


Old answer (related to Pyodide v0.15.0)

const output = document.getElementById("output")
const code = document.getElementById("code")

function addToOutput(s) {
    output.value += `>>>${code.value}\n${s}\n`
    output.scrollTop = output.scrollHeight
    code.value = ''
}

output.value = 'Initializing...\n'
// Init pyodide
languagePluginLoader.then(() => { output.value += 'Ready!\n' })

function evaluatePython() {
    pyodide.runPythonAsync(code.value)
        .then(output => addToOutput(output))
        .catch((err) => { addToOutput(err) })
}
<!DOCTYPE html>

<head>
    <script type="text/javascript">
        // Default Pyodide files URL ('packages.json', 'pyodide.asm.data', etc.)
        window.languagePluginUrl = 'https://cdn.jsdelivr.net/pyodide//v0.15.0/full/';
    </script>
    <script src="https://cdn.jsdelivr.net/pyodide//v0.15.0/full/pyodide.js"></script>
</head>

<body>
    Output:
    </div>
    <textarea id='output' style='width: 100%;' rows='10' disabled></textarea>
    <textarea id='code' rows='3'>
import numpy as np
np.ones((10,))
    </textarea>
    <button id='run' onclick='evaluatePython()'>Run</button>
    <p>You can execute any Python code. Just enter something
       in the box above and click the button.
       <strong>It can take some time</strong>.</p>
</body>

</html>

2
  • test snippet is no longer working Feb 24 at 13:15
  • Great! Nice work with an interesting toolkit. Feb 27 at 21:22
3

If your web server is Apache you can use the mod_python module in order to run your Python CGI scripts.

For nginx, you can use mod_wsgi.

1
  • 2
    The mod_python project is long dead and shouldn't be used for anything new. The option for Apache, not nginx as you have it, is mod_wsgi, but the Google Code site is old site which is no longer used, use modwsgi.org instead. Nov 29, 2016 at 11:59
1

There's a new tool, PyScript, which might be helpful for that.

Official website

GitHub repository

3
  • 1
    The examples in that GitHub repository are actively available to try online at pyscript.net/examples .
    – Wayne
    May 9, 2022 at 15:07
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – Emi OB
    May 12, 2022 at 15:13
  • This project is also based on Pyodide May 29, 2022 at 19:14
0

You can't run Python code directly

You may use Python Inside HTML.

Or for inside PHP this:

http://www.skulpt.org/
1
  • The second link is broken (DNS domain expiry?): "Hmm. We’re having trouble finding that site.. We can’t connect to the server at www.skulpt.org." May 29, 2022 at 16:26
0

You should try the Flask or Django frameworks. They are used to integrate Python and HTML.

0

There is a way to do it with Flask!

Installation

First you have to type pip install flask.

Setup

You said when a user clicks on a link you want it to execute a Python script

from flask import *
# Importing all the methods, classes, functions from Flask

app = Flask(__name__)

# This is the first page that comes when you
# type localhost:5000... it will have a tag
# that redirects to a page
@app.route("/")
def  HomePage():
    return "<a href='/runscript'>EXECUTE SCRIPT </a>"

# Once it redirects here (to localhost:5000/runscript),
# it will run the code before the return statement
@app.route("/runscript")
def ScriptPage():
    # Type what you want to do when the user clicks on the link.
    #
    # Once it is done with doing that code... it will
    # redirect back to the homepage
    return redirect(url_for("HomePage"))

# Running it only if we are running it directly
# from the file... not by importing
if __name__ == "__main__":
    app.run(debug=True)
0

You should use Py Code because it could run Any python script In html Like this:

<py-script>print("Python in Html!")<py-script>

Im not sure if it could run modules like Ursina engine ect But what i know is That It allows you to type Python in Html. You can check out its offical Site for more info.

1
  • You are probably referring to PyScript. But that answer has already been given.
    – chrslg
    Dec 30, 2022 at 16:45
0

We can use Python code in HTML files. We have to use Python’s libraries within our browsers.

As we use Pyscript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.

Pyscript allows us to write python code with the help of 3 main components:

  1. Py-env: It defines the python packages list which needs to run your code.
  2. Py-script: In this tag, the user will write their python code.
  3. Py-repl: It will Create a REPL component. The REPL component executes the code user enters and displays the result of the code in the browser.

Let's start:

<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />

Our Hello world program will look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
   <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
   <title>Python HTML app Hello World</title>
</head>
<body>
   <py-script>  
   print("Hello World!")
   </py-script>
</body>
</html>

This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. Let know more about how to use python in HTML file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.