python sys怎么用,如何使用通过sys模块运行的命令获取Python程序来杀死自己?

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)

EDIT: emphasising for clarity

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

解决方案

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

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).

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:~$

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

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

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:~$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值