【问题标题】:Killing a python server through shell interrupt通过shell中断杀死python服务器
【发布时间】:2017-11-30 21:06:06
【问题描述】:

我有一个 bash 脚本,它在后台运行一些 python 脚本。我已经给它们附加了一个中断信号,所以当我按 ctrl-c 时,我会从它们中逃脱。但是,我的 python 脚本启动了一个 SimpleHTTPServer。中断会终止 python 脚本,但不会终止 SimpleHTTPServer。我将如何结束该过程?

我在main-script.sh 中有以下外壳:

trap 'kill %1; kill %2' SIGINT
cd "$DIR_1" && ./script1.py &
cd "$DIR_2" && ./script2.py &
./script3.py 

python 脚本只是启动了一个带有一些额外标头的 SimpleHTTPServer。

在终端中运行ps x 会给出

60958 pts/1    S      0:00 /bin/bash ./main-script.sh
60959 pts/1    S      0:00 /bin/bash ./main-script.sh
60960 pts/1    S      0:02 /usr/bin/python ./script1.py host:port1
60962 pts/1    S      0:01 /usr/bin/python ./script2.py host:port2

在 ctrl-c 之后

60960 pts/1    S      0:02 /usr/bin/python ./script1.py host:port1
60962 pts/1    S      0:01 /usr/bin/python ./script2.py host:port2

这里编辑的是启动服务器的主要代码:

#!/usr/bin/python
import SimpleHTTPServer
import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

def test(HandlerClass=SimpleHTTPRequestHandler,
         ServerClass=BaseHTTPServer.HTTPServer):

    protocol = "HTTP/1.0"

    server_address = (host, port)
    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)
    httpd.serve_forever()

if __name__ == '__main__':
    test()

任何帮助将不胜感激。谢谢你。

【问题讨论】:

  • 包括启动服务器的代码,这取决于它
  • @ArtemBernatskyi 添加了代码片段。

标签: python bash shell simplehttpserver


【解决方案1】:

实际上并不完全确定这是否有效,因为我在 Windows 上,现在无法验证这一点。但是您的 python 实例应该是接收 Ctrl-C 信号(或称为 SIGINT)的那个。

这段代码应该可以在 Python 中工作:

import signal
from sys import exit
from os import remove

def signal_handler(signal, frame):
    try:
        ## == Try to close any sockets etc nicely:
        ##    s in this case is an example of socket().
        ##    Whatever you got, put the exit stuff here.
        s.close() 
    except:
        pass
    ## == If you have a pid file:
    remove(pidfile)
    exit(1)
signal.signal(signal.SIGINT, signal_handler)

## == the rest of your code goes here

这应该会捕获 SIGINT 并很好地停止。
如果所有其他方法都失败了,只会发生纯粹的关闭。

【讨论】:

  • @JoeFromAccounting Joe,来自会计部门,不客气。谢谢你提高了我的薪水。一切顺利//看门人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2021-06-27
  • 2012-04-22
相关资源
最近更新 更多