如何从html页面上的用户那里获取输入并在后台使用子流程stdin处理它,并在html上显示回来

时间:2019-02-15 02:30:51

标签: html flask subprocess

我正在使用flask和子进程制作一个在线python编译器,其中用户在html页面上编写一些代码,然后单击“运行”按钮,它将在后台处理并在html页面背面显示结果。到目前为止,它只能打印“ Hello World”之类的常规程序。现在我希望该用户也可以提供输入以执行一些任务。我不知道该怎么做。如果有人帮助我,我会很高兴。 这是代码:

import subprocess
from flask import Flask,render_template,request
from werkzeug import secure_filename
app = Flask(__name__)
@app.route('/')
def run_1():
    return render_template('compiler_html.html')
@app.route('/',methods=["POST"])
def done():
    with open("code_check.py","w") as file:
        data=str(request.form.get("code"))
        file.write(data)
    proc = subprocess.Popen(["python", "code_check.py"], stdout=subprocess.PIPE, shell=True ,
                            universal_newlines=True,stdin=subprocess.PIPE,stderr=subprocess.STDOUT)
    cd = str(proc.communicate()[0])
    print(cd)
    fill='File "code_check.py",'
    color = " "
    if fill in cd:
        color="red"
    else:
        color="#267326"

    return render_template('compiler_html.html',show=cd,color=color,return_code=data)

@app.route('/get',methods=["POST"])
def local_file():
    f = request.files['cfile']
    f.save("static/files/"+secure_filename(f.filename))
    print(f.filename)
    proc = subprocess.Popen(["python", "static/files/"+(f.filename)], stdout=subprocess.PIPE, shell=True ,
                            universal_newlines=True,stdin=subprocess.PIPE,stderr=subprocess.STDOUT)
    cd = str(proc.communicate()[0])

    #######################################################
    with open('static/files/'+(f.filename), "r") as fh:
        data=fh.read()
    #####################################################
    print(cd)
    fill=' File "static/files/'
    color=""
    if fill in cd:
        color="red"
    else:
        color="#267326"

    return render_template('compiler_html.html',show=cd,color=color,return_code=data)     


if __name__ == '__main__':
        app.run('localhost',5000)

html脚本::

<!DOCTYPE html>
<html>
    <head>


        <title>TEST COMPILER</title>
        <link rel="stylesheet" type="text/css" href="/static/compiler.css">

    </head>

    <!--START BODY ############################################################-->

    <body background="/static/project_bg_wallpaper.jpg" onload="setbackground()">

        <!--HEADER DIV#########################################################-->

        <div class="header_div">
            <h1 align="center"> PYTHON COMPILER</h1>
        </div>

        <!--LOCAL FILES AREA ################################################-->

        <form method="POST" action="{{url_for('local_file')}}" enctype = "multipart/form-data">
            <label class="custom-file-upload">
    <input name="cfile" id="check" type="file" class="cfile" required >
    Choose Local File
</label>
            &nbsp;&nbsp;&nbsp;
            <input type="submit" class="cfile" onclick="fun_check()" value="Run local Program">
        </form>
        <br>
        <br>

        <!-- INPUT AREA ####################################################-->
        <div>
            <div class="input_div">
                <form  method="POST" action="{{url_for('done')}}">
                    <textarea class="input_area" name="code"  id="online_code" rows="16" cols="55" placeholder="print('Hello World')" required>{{return_code}}</textarea>
                    <br><br>
                    <div class="button_div">
                        <input type="submit" onload="setbackground()"  onclick="check_online_code()" id="run_button" value="RUN" class="run_button">
                    </div>
                </form>
            </div>
            <!--OUTPUT DIV ####################################################-->
            <div style="color:{{color}}; font-weight: 550;" class="output_div">
                <pre>{{show}}</pre>
            </div>

        <!--JAVASCRIPT #########################################################-->
        <script>
            function setbackground()
            {
                window.setTimeout( "setbackground()", 200); // 200 milliseconds delay

                date = new Date;
                s = date.getSeconds();
                //var index = Math.round(Math.random() * 2);
                var textcolor;
                var ColorValue ;   //= "FFFFFF"; // default color - white (index = 0)
                if (s%2==0)
                    {
                        ColorValue = "#267326";
                        textcolor="#ffffff";
                    }
                else
                    {
                        ColorValue = "Transparent";
                        textcolor="#267326"; 
                    }


                var btn = document.getElementsByTagName("input")[2];
                btn.style.backgroundColor = ColorValue;
                btn.style.color=textcolor;
                //document.getElementById("run_button").style.color=textcolor;
                //document.getElementById("run_button")[0].style.color=textcolor;
                //setTimeout('date_time("'+id+'");','1000');
                return true;
            }

            /*  FOR TAB IN TEXTAREA #########################################*/

            var textareas = document.getElementsByTagName('textarea');
            var count = textareas.length;
            for(var i=0;i<count;i++)
            {
                textareas[i].onkeydown = function(e)
                {
                    if(e.keyCode==9 || e.which==9)
                    {
                        e.preventDefault();
                        var s = this.selectionStart;
                        this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
                        this.selectionEnd = s+1; 
                    }
                }
            }
            function  fun_check()
            {
                var check_value=document.getElementById('check').value;
                if(check_value==null || check_value=="")
                    {
                        alert("Select a file first !")
                    }
            }
            function check_online_code()
            {
                var check_value=document.getElementById("online_code").value;
                if(check_value==null || check_value=="")
                    {
                        alert("put some code in code box please!!")
                    }
            }


        </script>
    </body>
</html>

0 个答案:

没有答案