-2

I want to use shell commands in the flask function. Is there any way? The following is a server.py file I wrote. I want to use shell commands such as shell cd, ls, etc. in the ??? section.

from flask import Flask
app = Flask(__name__)

@app.route('/getFromHtml')
def func():
      ????


if __name__ == "__main__":
   app.run(host="127.0.0.1", port="5000")
Vladimir
  • 338
  • 7
  • 18

1 Answers1

1

Try this: https://docs.python.org/3/library/subprocess.html#subprocess.Popen

Example:

from subprocess import Popen, PIPE

from flask import Response

...

@app.route('/getFromHtml')
def func():
    process = Popen(["ls -lah /etc/"], stdout=PIPE)
    stdout, stderr = process.communicate()
    if stderr:
        stdout = f"error code = {stderr}"
    else:
        stdout = stdout.decode("utf-8")
    return Response(stdout)
Vladimir
  • 338
  • 7
  • 18