【windows&flask】flask通过service自动运行
最近在学习在windows平台用flask框架提供Restful API服务,需要使得flask的windows应用能够开机自动运行,并且后台运行,所以通过service来实现。
首先尝试的是在自己派生的serivice类的中直接调用 create_app(debug=True).run(host='0.0.0.0', port=5000) 的方式启动flask。
参考代码:
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager
import socket
import time import os
import sys
from flask import logging, app, Flask
from run import create_app sys.path.append(os.path.dirname(__name__)) def main():
# app.run(host="0.0.0.0", port=5000) # 服务运行函数
# launch()
create_app(debug=True).run(host='0.0.0.0', port=5000) class MySvc(win32serviceutil.ServiceFramework):
_svc_name_ = "my web service" # 服务名
_svc_display_name_ = "my web service" # 描述 def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(5)
self.stop_requested = False def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
# logging.info('Stopped service ...')
self.stop_requested = True def SvcDoRun(self):
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, '')
) main() if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MySvc)
但是启动service的时候一直报错如下,参考了很多种方法一直解决不了

接下来尝试用subprocess的方法拉起进程,成功!
class MyService(PySvc):
def start(self):
self.child = subprocess.Popen("python run.py", cwd="C:\\mytest")
logging.warning('child pid is %s',self.child.pid) # TODO: add run service code
def stop(self):
self.child.kill()
但是在stop的发现有一个python进程不能被kill。原因应该是flask本身会启动一个python子进程,相当于subprocess起了一个子进程执行 python run.py,在run.py启动flask的时候又启动了一个子进程,而child.kill只能杀死由subprocess启动的子进程,改成用taskkill就好了。
class MyService(PySvc):
def start(self):
self.child = subprocess.Popen("python run.py", cwd="C:\\mytest")
logging.warning('child pid is %s',self.child.pid) # TODO: add run service code
def stop(self):
#self.child.kill()
os.system("taskkill /t /f /pid %s" % self.child.pid)
完整代码如下:
import os
import signal
import subprocess
from time import sleep import win32service
import win32serviceutil
import win32event
import logging logging.basicConfig(filename='C:\\app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file') class PySvc(win32serviceutil.ServiceFramework):
_svc_name_ = "ServicePython" # NET START/STOP the service by the following name
_svc_display_name_ = "ServicePython Service" # name in the Service Control Manager (SCM)
_svc_description_ = "This service writes stuff to a file" # description in the SCM def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# create an event to listen for stop requests on , 所以也是可以和client进行通信的
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): # 启动时调用
import servicemanager
self.start()
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) def SvcStop(self): # 关闭时调用
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # tell the SCM
win32event.SetEvent(self.hWaitStop) # fire the stop event
self.stop() class MyService(PySvc):
def start(self):
self.child = subprocess.Popen("python run.py", cwd="C:\\mytest")
logging.warning('child pid is %s',self.child.pid) # TODO: add run service code
def stop(self):
os.system("taskkill /t /f /pid %s" % self.child.pid) # TODO:shut down the running flask web service if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
【windows&flask】flask通过service自动运行的更多相关文章
- mpush 服务端配置 for windows 服务自动运行
mpush 服务端配置 以下安装部分是参照官方的步骤, 一.安装jdk1.8并配置环境变量 示例: http://www.cnblogs.com/endv/p/6439860.html 二.Wind ...
- day92:flask:flask简介&基本运行&路由&HTTP请求和响应
目录 1.Flask简介 2.关于使用flask之前的准备 3.flask的基本运行 4.flask加载配置 5.传递路由参数(没有限定类型) 6.传递路由参数(通过路由转换器限定路由参数的类型) 7 ...
- Windows Server 2008 任务计划无法自动运行的解决办法
问题:编写的bat脚本,直接执行,成功:但是在任务管理器中配置该任务,运行不成功,结果显示为:0x1,系统环境为 Windows Server 2008. 分析:bat任务没有调用执行. 解决方案: ...
- C# 自动运行代码 (创建windows 服务的形式 )
本文转载自:http://blog.csdn.net/csethcrm/article/details/17917721 1. 新建项目 1.1 右键解决方案 – 添加 – 新建项目 1.2 ...
- 使用BroadcastReceiver实现开机自动运行的Service
为了让Service随应用系统启动自动运行,可以让BroadcastReceiver监听Action为ACTION_BOOT_COMPLETED常量的Intent,然后在BroadcastReceiv ...
- webstorm git 怎么断开版本控制 webstorm git for windows 禁止 自动运行
也是无语啊,今天装了下最新版本的webstorm , 发现特别卡,老动不动就卡死, 看了下进程, 牛X 啊, git for windows 一直蹭蹭蹭的疯狂增长,一开始的一点到后来的庞然大物. ...
- 设置Qt程序在Windows开机后自动运行
(转自:http://blog.csdn.net/weiren2006/article/details/7443362) 主要原理是修改Windows的注册表来实现的,Qt的QSettings提供了访 ...
- Windows平台,开机自动运行应用
打开注册表编辑器(Win+R后执行regedit) 进入HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run 新建字符串值, ...
- Windows下如何禁止优盘自动播放、自动运行
造冰箱的大熊猫@cnblogs 2019/1/28 为了防范层出不穷的病毒和木马,如何禁止插入优盘后Windows自动播放优盘或运行优盘程序? 运行环境:Windows 7 1)点击Windows开 ...
随机推荐
- Spring MVC -- 去掉静态资源的拦截
<!-- springmvc的前端控制器 --> <servlet> <servlet-name>springMVC</servlet-name> &l ...
- eventfd(2) 结合 select(2) 分析
本文代码选自内核 4.17 eventfd(2) - 创建一个文件描述符用于事件通知. 使用 源码分析 参考 #include <sys/eventfd.h> int eventfd(un ...
- 根据输入的整数n使得输出精确到小数n位
#include<iostream> #include<stdio.h> using namespace std; int main(){ int a,b,c; while(t ...
- navicat 系列软件一点击菜单栏就闪退
现象:安装多个版本都出现了闪退的现象 解决方案:后来发现,原来是启动了有道词典屏幕取词才会出现这种现象,关了有道就没事.
- Matlab学习笔记1—MATLAB基础知识
1.1 MATLAB系统环境 1.MATLAB操作界面的组成 (1)MATLAB主窗口 (2)命令行窗口:命令行窗口用于输入命令并显示命令的执行结果. (3) 当前文件夹窗口 如何设置当前文件夹呢? ...
- 数组被遗忘的内置对象--》Array.find()
需求:一个数组包含很多对象,对象中有很多属性.现在给你一个值,且这个值再这个数组的某个对象存在,那么如何找到这个对象? 首先想的是for循环遍历,但这样非常麻烦,js给我们提供了一个find()方法, ...
- idea 如何运行maven项目
1:run→Edit configurations 2:配置tomcat,左边如果没有tomcat server的话,点击 “+”,选择tomcat server→local,在右边server选项 ...
- python 并发编程 多进程 生产者消费者模型总结
生产者消费者模型总结 生产者消费者模型什么时候用? 1.程序中有两类角色 一类负责生产数据(生产者) 一类负责处理数据(消费者) 2.引入生产者消费者模型为了解决的问题是 平衡生产者与消费者之间的速度 ...
- mybatis使用的一点小结:session运行模式及批量提交(转)
mybatis的执行器有三种类型: ExecutorType.SIMPLE 这个类型不做特殊的事情,它只为每个语句创建一个PreparedStatement. ExecutorType.REUSE 这 ...
- Balloon Robot ZOJ - 3981
大意: n个参赛队, m个座位, 一共交了p次题, 一个机器人每秒钟会从位置$i$走到$i+1$, 若在$m$直接走到$1$, 当走到一个队伍就给该队应得的气球. 对于每道题, 假设交题时间$t_a$ ...