2012-03-13 63 views
0

我是Python的新手,我在異步調用和web服務器方面遇到了一些問題。後臺服務,SimpleHTTPServer和AJAX

我有一個SimpleHTTPServer通過AJAX與一個網站進行通信,該網站允許您在主機中啓動和停止服務。

問題是,我沒有得到我的HTTP:201,直到調用結束,這從來沒有發生,因爲這是一個長時間運行的過程。

我已經嘗試過調用,讓我的cmd在執行'cmd &'的shell腳本內也嘗試過Popen,我雖然是非阻塞的。

我也試圖與thread.start_new_thread(使用os.system(CMD))

def do_POST(self): 
    # ... some code to get args ... 
    subprocess.Popen([cmd, args]) 

    # I'd like 'cmd args' to run in the server while I return my HTTP:201 here 
    self.send_response(201) 
    self.end_headers() 
    self.wfile.write(output) 

回答

0

我發現這裏的解決方案:

Why does a background task block the response in SimpleHTTPServer?

def do_POST(self): 
    # ... some code to get args ... and output ... 
    subprocess.Popen([cmd, args]) 

    self.send_response(201) 
    self.send_header("Content-Length", str(len(output))) # This line does the trick! 
    self.end_headers() 
    self.wfile.write(output) 

否則蟒蛇保持打開狀態,直到後臺命令完成TCP連接。 指定您的響應的長度,蟒蛇發送TCP FIN和你的瀏覽器可以與它的生命:)

1

subprocess.Popen將在同一時間,你的代碼,這意味着你忽略了一些重要的東西在跑你的榜樣。

def demo(): 
    p = subprocess.Popen(['/bin/sleep', '2']) 
    n = 0 
    while p.poll() is None: 
     n+=1 
    return n 

print demo() # prints 1171552 on my machine... 

這意味着,蟒蛇/bin/sleep之前1171552倍左右,雖然環紡退出。

+0

感謝巴蒂爾進行,你是絕對正確的,過程是並行運行的,但我並沒有關閉連接適當。如果你好奇,請看看我自己的答案。 – 2012-03-14 10:13:01