退出 python 程序的最佳方法?

Best way to quit a python programme?

我觉得我问这个问题像个白痴,但 quit() 是终止 python 程序的最佳方式吗?或者有没有更好的方法可以逐渐停止所有 while True 循环等而不是立即停止所有循环?再一次,我觉得自己像个白痴问这个,但我只是好奇。

我不知道你为什么不想使用 quit() 但你可以使用这个:

import sys
sys.exit()

或者这样:

raise SystemExit(0)

要停止 while 循环,您可以使用 break 语句。例如:

while True:
    if True:
        do something  #pseudocode
    else:
        break

一旦 python

读取 else 语句,break 语句将立即停止 while 循环

您可以使用 break 语句来停止 while 循环。例如:

while True:
    if True:
        <do something>
    else:
        break

一般来说,结束一个Python程序的最好方法就是让代码运行完成。例如,在文件中查找 "hello" 的脚本可能如下所示:

# import whatever other modules you want to use
import some_module

# define functions you will use
def check_file(filename, phrase):
    with open filename as f:
        while True:
            # using a while loop, but you might prefer a for loop
            line = f.readline()
            if not f:
                # got to end of file without finding anything
                found = False
                break
            elif phrase in line:
                found = True
                break
    # note: the break commands will exit the loop, then the function will return
    return found

# define the code to run if you call this script on its own
# rather than importing it as a module
if __name__ == '__main__':
    if check_file("myfile.txt", "hello"):
        print("found 'hello' in myfile.txt")
    else:
        print("'hello' is not in myfile.txt")

# there's no more code to run here, so the script will end
# -- no need to call quit() or sys.exit()

请注意,一旦找到该短语或搜索到文件末尾,代码将跳出循环,然后脚本的其余部分将 运行。最终,脚本将 运行 出代码到 运行,并且 Python 将退出或 return 到交互式命令行。

如果您想停止 while True 循环,您可以将变量设置为 True 和 False,如果循环必须在特定数量的循环后停止,您甚至可以使用计数器。

例如

x = 0
y = True
while y == True:
    <do something>
    x = x + 1
    if x == 9:
        y = False

只是一个简单的例子,说明你可以做什么,而不使用 while 循环(基本上是我上面写的,但是在 1 行中。)

x = 10
for i in range(x):
    <do something>

要停止程序,我通常使用exit()break

我希望这能以某种方式帮助到你,如果没有的话;请发表评论,我会尽力帮助您!