【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开 ...
随机推荐
- kendo Ui实现搜索选中建议 不改变输入框的值
$("#SubjectFilter").kendoAutoComplete({ dataTextField: "patientCardNumber", temp ...
- QA Issue: PN: startUp is upper case, this can result in unexpected behavior. [uppercase-pn]
(借用一下) 该错误直接导致生成开机启动程序无法启动,既无法生成S99***快捷链接. 解决方法:仅仅将recpie lib-Test改成lib-test就可以了,即不要有大写字母. 附启动方法: S ...
- 【VS开发】ActiveX控件如何定制属性?
在很多场合下会存在这样的需求,那就是使用方在实际使用控件之前就想控件已经做了相应的处理比如加载的控件版本不正确等,或者需要在加载时才确定能够使用的功能集:这个时候传统的配置文件已经无法满足这种类型的需 ...
- qs.js使用方法
https://github.com/ljharb/qs 占个空
- c语言1作业07
这个作业属于那个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/CST2019-4/homework/9932 我在这个课程的目 ...
- mysql substr方法
mysql中的substr()函数 mysql中的substr()函数和hibernate的substr()参数都一样,就是含义有所不同. 用法: substr(string string,num s ...
- win10删除文件夹时需要管理员授权或拒绝访问(无权访问权限修改)
win10 用户:我自己就是电脑主人,凭啥我没有自己电脑文件夹的权限? 微软:对不起,您是电脑硬件的主人,但是电脑系统的主人是我!你只不过是个用户而已. win10 用户:我cao你...[哔-] 对 ...
- 【转载】Django自带的注册登陆功能
1.登陆 知识点: a.auth.authenticate(username=name值, password=password值) 验证用户名和密码 b.auth.login(request, use ...
- vue在组件中使用v-model
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- HTML5的几大新特性
为了更好地处理今天的互联网应用,HTML5添加了很多新元素及功能,比如: 图形的绘制,多媒体内容,更好的页面结构,更好的形式 处理,和几个api拖放元素,定位,包括网页 应用程序缓存,存储,网络工作者 ...