python - 调用另一个函数后重新启动一个函数
问题描述
我编写了一个 Python 函数来自动化软件程序。工作流程如下所示:
def main():
while True:
do A
if A is not done correctly for more than 100 times:
reboot()
while True:
do B
if B is not done correctly for more than 100 times:
reboot()
while True:
do C
if C is not done correctly for more than 100 times:
reboot()
def reboot():
restart the software program
我目前遇到的问题是,例如,如果 B 没有正确完成,它将触发重新启动。执行重启后,它会让我回到执行 B 的 while 循环。
我真正需要的是重新启动后始终从 A 开始的脚本。
我已经完成了我的研究,并且知道 Python 中没有 GoTo,人们建议对这种应用程序使用 while 循环,但我不知何故看不到它在我的情况下如何工作。任何建议将不胜感激,谢谢!
解决方案
Goto 是邪恶的,很容易造成一些重大的执行缺陷,这就是为什么在大多数专业环境中不再使用它的原因。
假设您的 A、B 或 C 是某种条件,在这种情况下,您可以创建一个评估该条件的函数,尽管它在很大程度上取决于条件是什么。
为什么不根据您拥有的任何业务逻辑以适当的条件调用函数。这就是我的建议:
def do_the_work(...condition params):
while True:
# do the actual work and evaluate the conditions
# if the conditions don't pass for X times
# then just break this loop and return
while True:
# main business logic here
# will decide how to call the
# do_the_work function
# meaning, deciding what params to send to it
解释是在脚本末尾定义的主while循环将是你的“main”,每次“do_the_work”结束它的while循环并返回时,它将重做工作。
推荐阅读
- recursion - Pygame 中的递归曲面
- javascript - 使用范围滑块更改 SVG 圆的半径
- python - 如何在 pandas 中对不同的数据框进行分组和聚合
- c++ - SFML 即使在覆盖虚拟绘图功能后也无法绘制对象
- php - 在 PHP 中搜索 MySQL 查询
- cassandra - Cassandra:使用强制转换函数错误将整数转换为十进制值
- c# - 微服务未在 LaunchSettings.JSON 设置的端口上启动
- c# - 为什么这个代码在我打开它后会改变我的主窗体背景颜色?
- java - 为什么迭代器中的修改在迭代期间不可见?
- reactjs - React native 获取和使用 usestate 来获取依赖的数据项