退出python程序的最佳方法是什么?

时间:2018-04-21 23:20:49

标签: python exit

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

4 个答案:

答案 0 :(得分:3)

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

import sys
sys.exit()

或者这个:

raise SystemExit(0)

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

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

break语句将在python

读取while语句后立即停止else循环

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

通常,结束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将退出或返回到交互式命令行。

答案 3 :(得分:1)

如果要停止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

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

相关问题