close

How can I run a python script from within Flask

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I run a python script from within Flask in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can I run a python script from within Flask

  1. How can I run a python script from within Flask

    You can use other functions such as subprocess.call et cetera; although they might not give you the response.

  2. I run a python script from within Flask

    You can use other functions such as subprocess.call et cetera; although they might not give you the response.

Method 1

Using import:

  • Wrap what the python script (e.g. website_generator.py) is generating into a function.
  • Place it in the same directory as your app.py or flask.py.
  • Use from website_generator import function_name in flask.py
  • Run it using function_name()

You can use other functions such as subprocess.call et cetera; although they might not give you the response.

Example using import:

from flask import Flask
import your_module # this will be your file name; minus the `.py`

app = Flask(__name__)

@app.route('/')
def dynamic_page():
    return your_module.your_function_in_the_module()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000', debug=True)

Method 2

try this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def run_script():
    file = open(r'/path/to/your/file.py', 'r').read()
    return exec(file)

if __name__ == "__main__":
    app.run(debug=True)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read