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

标签 python shell kill

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

os.system(killCommand)

编辑:强调清楚

所以,为了清楚起见,我想要一个在终止 Python 程序的 shell 中运行的字符串

最佳答案

可以使用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 - 我怎样才能让 Python 程序使用通过模块 sys 运行的命令来杀死自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065781/

相关文章:

php - 在 Linux 中的 PHP 脚本中终止所有相关进程

python - 使用 Python 处理一个巨大的 CSV 时, 'killed' 是什么意思,突然停止?

python - 在图像上绘制的好 python 模块

python - 交换数据框列数据而不更改表的索引

jquery - Django 延迟加载分页

python - subprocess.Popen.communicate 对于大数据集效率不高?

Bash Shell 当前日期减去天数

c - 信号处理程序中奇怪的 sleep 行为

perl - 如果我在构建 testcover 过程完成之前终止了它,我可以强制 Perl Devel::Cover 生成覆盖报告吗?

Python 多处理和 wxPython 协同工作