python - 使用 return 语句正确退出 while 循环
问题描述
我的 Flask 路线之一中有这个 while 循环。该函数的目的是从用户那里检索一个值并检查该 str 是否存在于目录中的任何文件名中。如果为真,则返回“plot_list”并退出函数。如果为 false,请等待 30 秒,然后再次检查该 str 是否存在于目录中的任何文件名中。
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
while True:
time.sleep(5)
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project, csv_path))
plot_list = ["basketball.html", "hockey.html"]
return jsonify(plot_list)
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project, csv_path,
(current_time - start_time)))
time.sleep(30)
这些是函数的打印语句:
Advanced csv was found in \static\csv\dist_drift
None csv not found in \static\csv\dist_drift after waiting 5.001329660415649 seconds!
["basketball.html", "hockey.html"]
None csv not found in \static\csv\dist_drift after waiting 35.00231146812439 seconds!
None csv not found in \static\csv\dist_drift after waiting 65.00326824188232 seconds!
我确信这是一个简单的解决方法,但我无法弄清楚。有什么帮助吗?
编辑:问题是即使 str 存在于目录中的文件名中,该函数也没有退出。
编辑2:这行得通。感谢您的提示。
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
time.sleep(5)
while True:
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project, csv_path))
subprocess.call(
[r'C:\Program Files\SAS\JMP\15\jmp.exe',
r'C:\Users\Gol69206\PycharmProjects\rel-dashboard\JSL\Plots.jsl'])
plot_list = ["basketball.html", "hockey.html"]
return jsonify(plot_list)
break
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project, csv_path,
(current_time - start_time)))
time.sleep(30)
解决方案
你在函数之外的回报。只需修复标签
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_Project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
time.sleep(5)
while True:
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project , csv_path))
plot_list = ["basketball.html", "hockey.html"]
print(plot_list)
return jsonify(plot_list)
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project , csv_path,
(current_time - start_time)))
time.sleep(30)
推荐阅读
- mkmapview - 地图视图快速水平翻转
- java - 在 groovy / java 中递归解析 XML
- c# - 错误上传/下载文件到/从便携式设备使用
- angular - Angular 6 Uncaught ReferenceError:未定义缓冲区
- iis - 在 ASP.NET 中使用模拟 使用 .NET Framework 4.6.1 在 IIS 中托管
- sql - 合并oracle中表中的两行,除生效日期外,所有详细信息都相同
- c - LTTng:用户应用程序跟踪致命错误
- python - 烧瓶中的数据库迁移 - sqlalchemy
- visual-studio-code - VS Code 中的 Jython 设置
- javascript - 如何使用 HTML 中的 onBlur 从服务器调用烧瓶函数?