我正在尝试将数据从一个进程传递到另一个烧瓶进程。尝试在烧瓶过程中使用全局变量,但我无法在进程之间传输数据。也尝试烧瓶作为线程,但它没有反应。法典:
from flask import Flask
from multiprocessing import Process, Queue
import time
globalvar=0
app = Flask(__name__)
@app.route('/')
def index():
return "globvar in index="+str(globalvar) # I want to return globvar
def multiprocess(q):
#global globalvar tried but same result
i=0
while 1: # for keep fresh value of i
i+=1
variable = i % 10
print "i in multiprocess=" + str(i)
q.put(variable)
time.sleep(1)
def flaskserver():
app.run(debug=True, host='127.0.0.1', port=7654,use_reloader=False)
if(__name__=='__main__'):
q = Queue()
p1 = Process(target=flaskserver)
p2 = Process(target=multiprocess, args=(q,))
p1.start()
p2.start()
while 1:
globalvar = q.get()
print "globalvar in main=" + str(globalvar)
time.sleep(3)
控制台输出:
/usr/bin/python /Users/macbook/Desktop/python/stack-flask-multi.py i in multiprocess=1 globalvar in main=1 * Running on http://127.0.0.1:7654/ (Press CTRL+C to quit) i in multiprocess=2 i in multiprocess=3 i in multiprocess=4 globalvar in main=2 i in multiprocess=5 i in multiprocess=6 i in multiprocess=7 globalvar in main=3 i in multiprocess=8 i in multiprocess=9 i in multiprocess=10 globalvar in main=4
浏览器中请求的页面:
127.0.0.1 - - [22/Mar/2018 01:28:00] "GET / HTTP/1.1" 200 -
在浏览器中返回 --> index=0 中的 globvar
我没有看到你的问题...这看起来像是在回答你的问题:
from flask import Flask
from multiprocessing import Process, Queue
import time
globalvar=0
app = Flask(__name__)
@app.route('/')
def index():
return "globvar in index=" + str(q.get()) # Now, it will return a value other than 0!
def multiprocess(q):
# global globalvar tried but same result
i = 0
while 1: # for keep fresh value of i
i += 1
variable = i % 10
print "i in multiprocess=" + str(i)
q.put(variable)
time.sleep(0.1)
def flaskserver():
app.run(debug=True, host='127.0.0.1', port=7654, use_reloader=False)
if (__name__ == '__main__'):
q = Queue()
p1 = Process(target=flaskserver)
p2 = Process(target=multiprocess, args=(q,))
p1.start()
p2.start()
while 1:
globalvar = q.get()
print "globalvar in main=" + str(globalvar)
time.sleep(0.1)