如何从 Flask 中运行 python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52835681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run a python script from within Flask
提问by Hyman022
I have a Flask
script which creates a website and prints some data dynamically. - The data which it prints should come from another python script.
我有一个Flask
创建网站并动态打印一些数据的脚本。- 它打印的数据应该来自另一个 python 脚本。
The current problem that I'm facing is that if I put the line that executes the python script before the line that executes the Flask
app, it will run the Python script without running Flask
; and vice versa.
我当前面临的问题是,如果我将执行 python 脚本的行放在执行Flask
应用程序的行之前,它将运行 Python 脚本而不运行Flask
; 反之亦然。
Python script:
蟒蛇脚本:
import websocket
from bitmex_websocket import Instrument
from bitmex_websocket.constants import InstrumentChannels
from bitmex_websocket.constants import Channels
import json
websocket.enableTrace(True)
sells = 0
buys = 0
channels = [
InstrumentChannels.trade,
]
XBTUSD = Instrument(symbol='XBTUSD',
channels=channels)
XBTUSD.on('action', lambda msg: test(msg))
def test(msg):
parsed = json.loads(json.dumps(msg))
print(parsed)
XBTUSD.run_forever()
Flask script (NB: price should be the variable 'parsed' from the other script):
Flask 脚本(注意:价格应该是从另一个脚本中“解析”出来的变量):
# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time
__author__ = 'slynn'
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
#turn the flask app into a socketio app
socketio = SocketIO(app)
#random number Generator Thread
thread = Thread()
thread_stop_event = Event()
class RandomThread(Thread):
def __init__(self):
self.delay = 1
super(RandomThread, self).__init__()
def randomNumberGenerator(self):
while not thread_stop_event.isSet():
socketio.emit('newnumber', {'number': parsed}, namespace='/test')
sleep(self.delay)
def run(self):
self.randomNumberGenerator()
@app.route('/')
def index():
#only by sending this page first will the client be connected to the socketio instance
return render_template('index.html')
@socketio.on('connect', namespace='/test')
def test_connect():
# need visibility of the global thread object
global thread
print('Client connected')
#Start the random number generator thread only if the thread has not been started before.
if not thread.isAlive():
print("Starting Thread")
thread = RandomThread()
thread.start()
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
回答by Julian Camilleri
Using import
:
使用import
:
- Wrap what the python script (e.g.
website_generator.py
) is generating into a function. - Place it in the same directory as your
app.py
orflask.py
. - Use
from website_generator import function_name
inflask.py
- Run it using
function_name()
- 将 python 脚本(例如
website_generator.py
)生成的内容包装到一个函数中。 - 将它放在与您的
app.py
或相同的目录中flask.py
。 - 使用
from website_generator import function_name
中flask.py
- 运行它使用
function_name()
You can use other functions such as subprocess.call
et cetera; although they might not give you the response.
您可以使用其他功能,例如subprocess.call
等;虽然他们可能不会给你答复。
Example using import
:
使用示例import
:
from flask import Flask
import your_module # this will be your file name; minus the `.py`
app = Flask(__name__)
@app.route('/')
def dynamic_page():
return your_module.your_function_in_the_module()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)