当前位置:首页> 正文

关于终止:终止python脚本

关于终止:终止python脚本

Terminating a Python script

我知道PHP中的die()命令会提前停止脚本。

我怎么能用python做这个呢?


1
2
import sys
sys.exit()

sys模块文档的详细信息:

sys.exit([arg])

Exit from Python. This is implemented by raising the
SystemExit exception, so cleanup actions specified by finally clauses
of try statements are honored, and it is possible to intercept the
exit attempt at an outer level.

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. Most systems
require it to be in the range 0-127, and produce undefined results
otherwise. Some systems have a convention for assigning specific
meanings to specific exit codes, but these are generally
underdeveloped; Unix programs generally use 2 for command line syntax
errors and 1 for all other kind of errors. If another type of object
is passed, None is equivalent to passing zero, and any other object is
printed to stderr and results in an exit code of 1. In particular,
sys.exit("some error message") is a quick way to exit a program when
an error occurs.

Since exit() ultimately"only" raises an exception, it will only exit
the process when called from the main thread, and the exception is not
intercepted.

< /块引用>

请注意,这是退出的"好"方式。@下面的glyphTwistedMatrix指出,如果你想要一个"硬退出",你可以使用os.u exit(错误代码),尽管它在某种程度上可能是操作系统特有的(例如,它可能不采用Windows下的错误代码),而且它肯定不太友好,因为它不让解释器在进程结束之前进行任何清理。


尽早终止Python脚本的一个简单方法是使用内置函数quit()。不需要导入任何库,而且它是高效和简单的。

例子:

1
2
3
#do stuff
if this == that:
  quit()


另一种方法是:

1
raise SystemExit

虽然您通常更喜欢sys.exit,因为它比其他代码更"友好",但实际上它所做的只是引发一个异常。

如果您确定需要立即退出一个进程,并且您可能在某个异常处理程序中,该异常处理程序会捕获SystemExit,那么还有另一个函数os._exit,该函数会立即在C级别终止,并且不会执行解释器的任何正常下拉操作;例如,用"at exit"注册的钩子。未执行模块。


您也可以简单地使用exit()

记住,sys.exit()exit()quit()os._exit(0)会杀死python解释器。因此,如果它出现在由execfile()从另一个脚本调用的脚本中,它将停止两个脚本的执行。

请参见"停止执行用execfile调用的脚本"以避免这种情况。


1
2
from sys import exit
exit()

作为一个参数,您可以传递一个退出代码,该代码将返回到OS。默认值为0。


我刚刚发现,在编写多线程应用程序时,raise SystemExitsys.exit()都只会杀死正在运行的线程。另一方面,os._exit()退出了整个过程。这在这里讨论过。

下面的示例有两个线程。肯尼和卡特曼。卡特曼应该永远活下去,但肯尼是递归调用,应该在3秒后死亡。(递归调用不是最好的方法,但我有其他原因)

如果我们也希望卡特曼死在肯尼死的时候,肯尼应该和埃多克斯离开,否则,只有肯尼会死,卡特曼会永远活下去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import threading
import time
import sys
import os

def kenny(num=0):
    if num > 3:
        # print("Kenny dies now...")
        # raise SystemExit #Kenny will die, but Cartman will live forever
        # sys.exit(1) #Same as above

        print("Kenny dies and also kills Cartman!")
        os._exit(1)
    while True:
        print("Kenny lives: {0}".format(num))
        time.sleep(1)
        num += 1
        kenny(num)

def cartman():
    i = 0
    while True:
        print("Cartman lives: {0}".format(i))
        i += 1
        time.sleep(1)

if __name__ == '__main__':
    daemon_kenny = threading.Thread(name='kenny', target=kenny)
    daemon_cartman = threading.Thread(name='cartman', target=cartman)
    daemon_kenny.setDaemon(True)
    daemon_cartman.setDaemon(True)

    daemon_kenny.start()
    daemon_cartman.start()
    daemon_kenny.join()
    daemon_cartman.join()

我是个新手,但这肯定更干净,更可控。

1
2
3
4
5
6
7
8
9
10
11
def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        return
    print 'You wont see this'

if __name__ == '__main__':
    main()

Program terminated

1
2
3
4
5
6
7
8
9
10
11
12
import sys
def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        sys.exit()
    print 'You wont see this'

if __name__ == '__main__':
    main()

Program terminated Traceback (most recent call last): File"Z:\Directory\testdieprogram.py", line 12, in
main() File"Z:\Directory\testdieprogram.py", line 8, in main
sys.exit() SystemExit

< /块引用>

编辑

关键是,该计划的结束顺利和平,而不是"我已经停止了!!!!"


在python 3.5中,我尝试在不使用内置模块(例如sys、biopy)的情况下合并类似的代码,以停止脚本并向我的用户打印错误消息。下面是我的例子:

1
2
3
4
5
6
## My example:
if"ATG" in my_DNA:
    ## <Do something & proceed...>
else:
    print("Start codon is missing! Check your DNA sequence!");
    exit(); ## as most folks said above

稍后,我发现只抛出一个错误更为简洁:

1
2
3
4
5
## My example revised:
if"ATG" in my_DNA:
    ## <Do something & proceed...>
else:
    raise ValueError("Start codon is missing! Check your DNA sequence!");

展开全文阅读

相关内容