Berlin Bolin
Berlin Bolin

Reputation: 87

Execute linux command in Python Flask

How can I execute linux command inside a Python function? I will run the python file in a linux-based server, and in some functions I want to have something like,

def function():
    #execute some commands on the linux system, eg. python /path1/path2/file.py

    # Or execute a shell script, eg. /path1/path2/file.sh

What python module do I need to achieve this?

Thanks in advance.

Upvotes: 2

Views: 7633

Answers (2)

dedunu
dedunu

Reputation: 172

This code will create a flask server and allow you to run commands. You can also capture the output.

import subprocess

from flask import Flask
app = Flask(__name__)

def run_command(command):
    return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()

@app.route('/<command>')
def command_server(command):
    return run_command(command)

You can run it by saving above text in server.py

$ export FLASK_APP=server.py
$ flask run

enter image description here

Upvotes: 3

justahuman
justahuman

Reputation: 637

Try the following:

import os, subprocess

# if you do not need to parse the result
def function ():
    os.system('ls')

# collect result
def function(command):
    out = subprocess.run(
        command.split(" "),
        stdout=subprocess.PIPE) 
    return out.stdout

Upvotes: 0

Related Questions