我怎样才能让 Python 程序通过模块 sys 使用命令 运行 杀死自己?

How can I get a Python program to kill itself using a command run through the module sys?

我想看看 Python 程序如何通过使用模块 sys 发出命令来杀死自己。我怎样才能让它使用以下形式的命令杀死自己?:

os.system(killCommand)

编辑:为清楚起见强调

所以,为了清楚起见,我想要一个 string 在 shell 中得到 运行 杀死 Python程序。

sys.exit(1) 将终止当前程序。参数为退出状态,非0表示异常终止。

实际上 sys.exit 的用途是:

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.

可以使用sys.exit()正常退出程序

Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure).


杀死解释器本身的系统命令取决于使用的shell;如果您的 shell 是 bashzsh,您可以使用:

a@host:~$ python
Python 2.7.8 (default, Oct 20 2014, 15:05:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system('kill $PPID')
Terminated
a@host:~$

虽然您的实际结果可能会有所不同。为了更安全,你需要自己提供进程ID:

>>> os.system('kill %d' % os.getpid())

如果你只想向你的进程发送一个get信号,你也可以使用os.kill()和你进程的进程id;当前 运行 进程的进程 ID 可从 os.getpid():

获得
a@host:~$  python
Python 2.7.8 (default, Oct 20 2014, 15:05:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.kill(os.getpid(), 9)
[1]    27248 killed     python
a@host:~$ 

如果您在主进程中(即您的邮件 python 脚本),您可以使用 os 模块

import os
import signal

#Your Python code
os.kill(os.getpid(),signal.SIGKILL)