如何在 Python 中使用 sys.exit()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14639077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:01:08  来源:igfitidea点击:

How to use sys.exit() in Python

pythonpython-3.xexit

提问by user2027690

player_input = '' # This has to be initialized for the loop

while player_input != 0:

    player_input = str(input('Roll or quit (r or q)'))

    if player_input == q: # This will break the loop if the player decides to quit

        print("Now let's see if I can beat your score of", player)
        break

    if player_input != r:

        print('invalid choice, try again')

    if player_input ==r:

        roll= randint (1,8)

        player +=roll #(+= sign helps to keep track of score)

        print('You rolled is ' + str(roll))

        if roll ==1:

            print('You Lose :)')

            sys.exit

            break


I am trying to tell the program to exit if roll == 1but nothing is happening and it just gives me an error message when I try to use sys.exit()

我试图告诉程序退出,如果roll == 1但没有发生任何事情,它只是在我尝试使用时给我一条错误消息sys.exit()



This is the message that it shows when I run the program:

这是我运行程序时显示的消息:

Traceback (most recent call last):
 line 33, in <module>
    sys.exit()
SystemExit

回答by Abhijit

sys.exit()raises a SystemExitexception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit

sys.exit()引发一个SystemExit异常,您可能将其假设为某些错误。如果您希望您的程序不引发 SystemExit 而是优雅地返回,您可以将您的功能包装在一个函数中并从您计划使用的地方返回sys.exit

回答by Jon Clements

Using 2.7:

使用 2.7:

from functools import partial
from random import randint

for roll in iter(partial(randint, 1, 8), 1):
    print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'

you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!

Then change the "oops" print to a raise SystemExit

然后将“oops”打印更改为 raise SystemExit

回答by godidier

I think you can use

我想你可以用

sys.exit(0)

You may check it herein the python 2.7 doc:

你可以检查它这里在Python 2.7 DOC:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

可选参数 arg 可以是给出退出状态的整数(默认为零)或其他类型的对象。如果是整数,则零被认为是“成功终止”,任何非零值都被壳等认为是“异常终止”。

回答by Pedro Fontes

you didn't import sys in your code, nor did you close the () when calling the function... try:

您没有在代码中导入 sys ,也没有在调用函数时关闭 () ......尝试:

import sys
sys.exit()