如何使用通过sys模块运行的命令获取Python程序来杀死自己? [英] How can I get a Python program to kill itself using a command run through the module sys?

查看:172
本文介绍了如何使用通过sys模块运行的命令获取Python程序来杀死自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to see how a Python program could kill itself by issuing a command using the module sys. How could I get it to kill itself using a command of the following form?:

os.system(killCommand)


强调清晰性


emphasising for clarity

因此,为了清楚起见,我想有一个 string 可以在杀死Python程序的外壳中运行.

So, just to be clear, I want to have a string that gets run in the shell that kills the Python program.

推荐答案

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

You can use sys.exit() to exit the program normally.

通过提高SystemExit(status)退出解释器. 如果状态被省略或None,则默认为零(即成功). 如果状态为整数,它将用作系统退出状态. 如果是另一种对象,则将其打印出来,然后系统 退出状态将为1(即失败).

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 ;如果您的外壳是bashzsh,则可以使用:


The system command to kill the interpreter itself depends on the shell used; if your shell is bash or zsh, you can use:

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:

Though your actual results may vary. To be safer, you need to provide the process ID yourself:

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


如果您只想将get信号发送到您的进程,则还可以将os.kill()与您的进程的进程ID一起使用;可从os.getpid()获得当前正在运行的进程的进程ID:


If you want to just a get signal sent to your process, you can also use os.kill() with the process id of your process; the process id of currently running process is available from 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:~$ 

这篇关于如何使用通过sys模块运行的命令获取Python程序来杀死自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆