Skip to content Skip to sidebar Skip to footer

How Can I Run A Python Script From Within Flask

I have a Flask script which creates a website and prints some data dynamically. - The data which it prints should come from another python script. The current problem that I'm faci

Solution 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('/')defdynamic_page():
    return your_module.your_function_in_the_module()

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

Solution 2:

try this:

from flask import Flask

app = Flask(__name__)

@app.route('/')defrun_script():
    file = open(r'/path/to/your/file.py', 'r').read()
    returnexec(file)

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

Post a Comment for "How Can I Run A Python Script From Within Flask"