我想看看 Python 程序如何通过使用模块 sys
发出命令来杀死自己。我怎样才能使用以下形式的命令让它自杀?:
os.system(killCommand)
编辑:强调清楚
所以,为了清楚起见,我想要一个在终止 Python 程序的 shell 中运行的字符串。
最佳答案
可以使用sys.exit()
正常退出程序。
Exit the interpreter by raising
SystemExit(status)
. If the status is omitted orNone
, 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 是 bash
或 zsh
,您可以使用:
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 - 我怎样才能让 Python 程序使用通过模块 sys 运行的命令来杀死自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065781/