首页 > 解决方案 > 调用另一个函数后重新启动一个函数

问题描述

我编写了一个 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 循环,但我不知何故看不到它在我的情况下如何工作。任何建议将不胜感激,谢谢!

标签: pythonpython-3.x

解决方案


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循环并返回时,它将重做工作。


推荐阅读