Python函数中的for循环阻止函数的进一步迭代 [英] for-loop in Python Function Prevents Further Iterations of Function from Working

查看:71
本文介绍了Python函数中的for循环阻止函数的进一步迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Flask应用程序,该应用程序运行的Python函数无法正常运行.我已经确定问题的根源是一个函数中的for循环,但是我不明白为什么会造成问题或如何产生问题.

I have a Flask application that runs python functions that isn't working properly. I have identified the source of the problem to be a for loop within a function, but I don't understand why it creates an issue or how.

我的flask应用程序启动了一个网络服务器,该服务器允许用户按下按钮以选择按ID搜索"或按日期搜索".然后,这会将他们定向到与他们选择的搜索相对应的不同页面,并允许他们执行搜索,从而在新选项卡中显示一个包含结果的html文件.然后,搜索页面通过选择按钮重定向回到原始页面.该应用程序的代码如下:

My flask application launches a webserver that allows users to press a button to select "searching by ID" or "searching by date." This then directs them a different page corresponding to their choice of search, and allows them to perform the search which brings up an html file containing the results in a new tab. The search page then redirects back to the original page with button selection. The code for the app is as follows:

from flask import Flask, render_template, redirect, request, url_for
from xml_identifiersearch import searchXML, printHTML

app = Flask(__name__)

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

@app.route('/', methods=['POST'])
def gateway():
    if request.form['submit'] == 'Identifier Search':
        return redirect(url_for('identifier_home'))
    else:
        return redirect(url_for('date_home'))

@app.route('/id/')
def identifier_home():
    return render_template('id_home.html')

@app.route('/id/', methods=['POST'])
def identifier_search():
    printHTML(request.form['input'])
    return redirect(url_for('index'))

@app.route('/date/')
def date_home():
    return render_template('date_home.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,debug=True)

问题出在函数"printHTML"上,当我的主体中不包含for循环时,此函数将正常工作,但是一旦执行,就开始出现问题.该函数的代码如下:

The problem, lies in the function "printHTML" This function works properly when I do not include the for loop in its body, but once I do, problems start arising. The code for the function is as follows:

from xml.dom import minidom
import glob
import os
import webbrowser
import random

def searchXML(identifier):
    li = []
    os.chdir('/Users/dinakarguthy/Documents/audit_sample')
    for files in glob.glob("*.xml"):
        with open(files) as f:
            contents=f.read()
        if identifier in contents:
            li.append(files)
    return li

def printHTML(search):    

    f = open("output.html", "w")           #output to a single html file

    print >>f, '<html><head><link rel="stylesheet" type="text/css" href="my_style.css"></head><body><table border="1">'

    print >>f, random.random()*100

    for fileName in searchXML(search):           #search and print a row for each file

        xmldoc=minidom.parse('/Users/dinakarguthy/Documents/audit_sample/' + fileName)   #parse the file
        commonBase=xmldoc.childNodes[1]
        contextData=commonBase.childNodes[1]
        contextValue = contextData.childNodes[1]
        y = contextValue.childNodes[0]

        print >>f, "<tr>"                                                                    
        print >>f, "<td rowspan = '2'>" + fileName + "</td>"                                          
        print >>f, "</tr>"

        print >>f, "<tr>"
        for data in xmldoc.getElementsByTagName('extendedDataElements'):                   #Descriptions
            print >>f, "<td>"
            print >>f, "</td>"

        print >>f, "</tr>"


     print >>f, "</table></body></html>"

    f.close()
    """open html page that was created on webbrowser"""
    new=2
    url="file:///Users/dinakarguthy/Documents/main3/output.html"
    webbrowser.open(url,new=new)

问题出在这里:当我包含以'p'开头的for循环时

Here is the problem: when I include the for loop that starts with

for filenames in searchXML(search):

整个功能仅在我第一次调用时起作用.每次之后,当我调用该函数时,它仍然运行并且我的flask应用程序运行良好,但是所有函数在行之间(包括行之间)进行调用

The entire function only functions the first time I call it. Every time afterwards, when I call the function, it still runs and my flask app works fine, but all of the function calls between and including the lines

f = open('output.html', 'w')
f.close()

不要跑.该功能在该行下方的部分

don't run. The part of the function below the line

f.close()

仍在运行.因此,仍将打开一个新选项卡,显示文件output.html,但该文件的其余功能尚未覆盖或截断该文件.可以通过以下事实证明这一事实:每次函数运行时都会生成并显示在文件的顶部,但是该随机数不再更改.

still runs. So a new tab is still opened displaying the file output.html, but the file has not been written over or even truncated by the rest of the function. This is evidenced by the fact that the random number is generated and displayed at the top of the file every time the function runs, but this random number no longer changes.

但是,在没有for循环的情况下,该函数正常运行,并且每次都会将新的随机数写入文件.使用for循环,它只能在第一次运行,之后每次都无法运行该行

Without the for loop however, the function works properly and a new random number is written to the file every time. With the for loop, it only works the first time and every time afterwards it fails to run the line

 f = open('output.html', 'w')

及其下的所有相关内容.更奇怪的是,如果我添加了其他执行类似功能的功能,那么我什至无法输出或写入 OTHER 文件.如果我在没有for循环的情况下运行其他功能,则所有功能都将正常运行,直到使用for循环运行此功能,然后再无任何输出.

and everything associated under it. What is even more curious is that if I add other functions that do similar things, I can't even output or write to OTHER files either. If I run the other functions without for loops, everything functions properly, until I run this function with the for loop and then nothing can be output anymore.

我知道这是一个很长的问题,但是我真的很感谢您的帮助,因为所有发生的事情都没有任何意义.

I know this is a long question but I would really appreciate some help because none of what is going on makes any sense.

推荐答案

我自己解决了这个问题.问题出在函数"searchXML"中,该函数在for循环中被调用.函数利用行

I have solved this myself. The problem lies in the function "searchXML", which is called in the for loop. The function utilizes the line

os.chdir('/Users/dinakarguthy/Documents/audit_sample')

但是打开文件的行只是

f = open('output.html', 'w')

我用相对路径名而不是绝对路径名打开文件,这就是问题所在.在for循环运行后,我的目录更改为另一个目录,因此在该otehr目录中创建/编辑了一个不同的output.html文件.但是,我的函数仍然会打开一个标签,其中的'output.html'仍在原始目录中.

I open the file with a relative pathname, instead of an absolute, which is the problem. After the for loop is run my directory is changed to a different one, and so a different output.html file is created/edited in that otehr directory. However, my function still opens up a tab with the 'output.html' that is still in the original directory.

这篇关于Python函数中的for循环阻止函数的进一步迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆