2017-02-13 138 views
2

我在jupyter筆記本使用SimpleHTTPServer這樣的:停止SimpleHttpSever在jupyter筆記本

import SimpleHTTPServer 
import SocketServer 

PORT = 8000 

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler 

httpd = SocketServer.TCPServer(("", PORT), Handler) 

print "serving at port", PORT 
httpd.serve_forever() 

它的工作原理很好,但我怎麼能以後停止它在接下來的輸入塊?

+0

Linux或OSX? – mtt2p

+0

'httpd.shutdown()'不能爲你工作嗎? – 9000

+0

@ 9000準確!這個命令確實對我的失敗了。該命令執行時沒有錯誤,但服務器仍在運行。 – matousc

回答

1

答案是你不能。

有關討論的更多詳細信息,您無法引用Jupyter Notebook內部的以前的單元格(或結果) - see this open issue

這意味着您在使用serve_forever()函數後無法操作對象。

但是可以重寫serve_forever以適應您的需求。目前,無論添加一個允許連接併發出「關閉」命令的條件,它都將從字面上起作用,以避免稍後調用對象。您可以連接到套接字併發出一個自定義的頭文件,TCP服務器將採集並響應。

作爲一個簡單的例子來開始你這條道路上:

class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): 

    def serve_forever(self): 
      while not self.stopped: 
       self.handle_request() 

    def not_forever(self): 
     # Called from another function when a custom header is detected 
     self.stopped = True 
     self.server_close() 
0

服務器在後臺運行,你需要搜索PID的殺死它想:

netstat -tulpn 

的Netstat出來:

tcp 0 0 0.0.0.0:8888 0.0.0.0:* LISTEN  12332/python 

殺PID與pkill的或殺:

kill 12332 
+0

這些命令是針對終端的,不是嗎?這是如何適用於jupyter筆記本? – matousc

+0

@matousc:假設你在Posix系統上運行,你可以使用'Popen',解析輸出等來運行這些命令。問題是,'kill'可能會殺死整個Jupyter進程,而不僅僅是HTTP服務器。 – 9000