0

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.pyspawns 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?

1 Answer 1

0

You can use subprocess.check_output

example:

result = subprocess.check_output(['ls', '-l'])
if result is not None:
    print(result.decode('utf-8'))

Otherwise you can also try with subprocess.Popen:

result = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0]

or:

p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result, err = p.communicate()
print(result.decode('utf-8'))

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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