python代码无法逐行读取并执行操作

时间:2019-06-13 00:26:56

标签: jquery json python-3.x flask

我正在编写python代码以创建一个Web服务来ping IP地址并在网页上显示结果。

我将flask代码写到ping IP地址并在同一页面上显示它们。但是,我的代码只能读取第一行并执行ping操作,并在第二个textarea框中显示结果。

您能说说我从文本文件中逐行读取内容中缺少的内容吗?

from flask import Flask, jsonify, render_template, request
import re, os

app = Flask(__name__)


@app.route('/_add_numbers')
def add_numbers():
    a = request.args.get('a', 0, type=str)

    def buffer_data():
        store_data = []
        var1 = str(a)
        with open("Bufferfile.txt", 'w', encoding='utf-8') as infile:
            for line in a:
                textdata1 = infile.write(line.strip(''))
            print("Done")
        with open("Bufferfile.txt", 'r', encoding='utf-8') as infile1:
            for row in infile1.read().rsplit():
                #print(row)
                # return(row)
                match1 = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:/\d{1,2}|)", row, re.MULTILINE)
                if match1:
                    ip = match1.group(0)
                    x = os.system("ping -n 1 " + ip)
                    if x == 0:
                        store_data.append(row + "--Active" + "\n")
                        #return (row + "--Active" + "\n")
                        print(row, "--Active" + "\n")

                    else:
                        store_data.append(row + "--Active" + "\n")
                        #return (row +"--Inactive" + "\n")
                        print(row, "Inactive" + "\n")

            #data2 = infile1.read()
            return (store_data)
            print("complete")
    return jsonify(result=buffer_data())


@app.route('/')
def index():
    return render_template('test3.html')


if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{
  url_for('static', filename='jquery.js') }}">\x3C/script>')
</script>

<script type=text/javascript>
  $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};

</script>

<script type=text/javascript>
  $(function() {
    $('a#calculate').bind('click', function() {
      $.getJSON($SCRIPT_ROOT + '/_add_numbers', {
        a: $('textarea[name="a"]').val()
      }, function(data) {
        $("#result").text(data.result);
      });
      return false;
    });
  });

</script>
<h1>jQuery Example</h1>
<p><textarea type=text size=5 name=a> </textarea> =
    <textarea type=text id=result>Get the result here!..</textarea>
<p><a href=# type=submit id=calculate>Get Result!</a>

1 个答案:

答案 0 :(得分:0)

您仅在for row...循环中返回一行。

您可能希望将每行追加到数组中,而不是返回,并返回:

def buffer_data():
    your_data = []

,并将两个return (row...都替换为your_data.append(row...)