2017-06-27 9 views
0

バックグラウンドでいくつかのPythonスクリプトを実行するbashスクリプトがあります。私はそれらに割り込み信号を添付しています。そのため、Ctrl-Cを押すと、それらのすべてから脱出します。しかし、私のpythonスクリプトは、SimpleHTTPServerを開始します。割り込みはpythonスクリプトを殺しますが、SimpleHTTPServerを強制終了しません。私はどのようにしてそのプロセスを終わらせることになるでしょうか?シェル割り込みによるPythonサーバーの強制終了

私は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() 

どれでも助けていただければ幸いです。ありがとうございました。

+0

サーバーを起動するコードが含まれています。それに依存します。 –

+1

@ArtemBernatskyiコードスニップを追加しました。 – JoeFromAccounting

答えて

2

これは私が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をキャッチし、きれいに停止する必要があります。
他のすべてが失敗した場合、純粋なシャットダウンだけが発生します。

+0

すごくうれしく、ありがとう! – JoeFromAccounting

+0

@JoeFromAccounting Joe、会計から、あなたは大歓迎です。私の給料を上げてくれてありがとう。すべての最高/ /管理人。 – Torxed

関連する問題