I'm building a Flask application that allows a user to execute python scripts and see its output in the body of the http response.
The following code works but I'm not able to return the output of the child process to the father's in order to return a html response with the script output.
For example, in the app.py
file I use the following code to run a subprocess that executes the client requested python script.
@app.route('/scripts/<script_name>')
def exec_script(script_name):
if os.path.isfile(os.path.join(app.config['SCRIPT_FOLDER'], script_name)):
result = subprocess.run(['python', os.path.join(app.config['SCRIPT_FOLDER'], script_name)], stdout=subprocess.PIPE, cwd=app.config['SCRIPT_FOLDER'])
print(result.stdout.decode('utf-8'))
# return HTML_PAGE
Let's suppose that the requested script example.py
spawns a process that executes a shell command, I'm not able to pass the output of the shell command to the process that was run in app.py
example.py
import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
I guess that the reason why this is happening is that the process created in app.py
is completed before the one created in the script. Is there a way to redirect the shell command output to the main application?