这是我要实现的目标的降低要求。
# run.py
import requests
import time
from subprocess import Popen, PIPE
server = Popen("./app.py", stdout=PIPE, stderr=PIPE, shell=True)
time.sleep(1)
res = requests.get("http://localhost:1234/")
assert res.status_code == 200
server.kill()
server.terminate()
res = requests.get("http://localhost:1234/")
print res
以及实际的服务器脚本。
#!/usr/bin/env python
from flask import Flask, make_response, request
app = Flask(__name__)
@app.route('/')
def view():
return make_response("")
if __name__ == "__main__":
app.run(host="localhost", port=1234)
在命令行上,我运行 python run.py
。来自外壳:
(t)yeukhon@fubini:/tmp$ ps aux|grep app
yeukhon 21452 0.6 0.4 16416 9992 pts/2 S 03:50 0:00 python ./app.py
yeukhon 21471 0.0 0.0 4384 804 pts/2 S+ 03:51 0:00 grep --color=auto app
所以 app.py
仍然卡在那里。我必须从命令行杀死它。事实上,run.py
的最后一行告诉我们服务器仍然存在(返回 200)。
我尝试用 os.kill(server.pid, signal.SIGTERM)
和 os.kill(server.pid, signal.SIGKILL)
杀死,但都不起作用.
通常kill
会起作用,但我真的不知道为什么它收不到信号。我确定 Flask 以某种方式拒绝停止。
我有哪些选择?
奇怪的是,我上面的脚本在 Mac OSX 上工作得很好(我在 10.8.5,Mountain Lion)。到目前为止,我已经在两台 Ubuntu 12.04 机器上进行了测试,它们具有相同的行为。我在 Ubuntu 机器上运行 Python 2.7.3,在我的 Mac OSX 上运行 Python 2.7.2。
更正: 我唯一的选择是使用 http://flask.pocoo.org/snippets/67/ .但我不想这样做。是的,我必须使用 Popen 启动一个。
最佳答案
通过指定shell=True
,命令由子shell运行。
server = Popen("./app.py", stdout=PIPE, stderr=PIPE, shell=True)
server.terminate
将终止子 shell,但不会终止 Web 服务器。
如何验证?在 Popen
调用之后尝试 print server.pid
,并将其与 ps
输出进行比较。
关于python - 无法杀死 Popen 在 Ubuntu 上启动的 Flask 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21824534/