【发布时间】:2014-03-16 11:32:11
【问题描述】:
这是我想要达到的降低要求。
# 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 启动一个。
【问题讨论】:
-
嗨 CppLearner。我遇到了同样的问题。但是,似乎我必须设置 shell=True 才能通过 popen 运行烧瓶。否则,我会收到类似“raise child_exception OSError: [Errno 2] No such file or directory”的错误消息。因此,我想知道您最终是如何修改代码的。当 shell=True 时,服务器从 popen 启动,继续运行。