【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开 ...
随机推荐
- IOS CocoaPods详细使用方法
自从有了CocoaPods以后,这些繁杂的工作就不再需要我们亲力亲为了,只需要我们做好少量的配置工作,CocoaPods会为我们做好一切 一.什么是CocoaPods 1.为什么需要CocoaPo ...
- Markdown基础语法总结
目录 区块元素 标题 列表 区块引用 代码区块 分隔线 段落和换行 区段元素 链接 强调 代码 图片 转义 标题 <a name="title"></a> ...
- dos2unix Linux解决编写脚本出现“%0D
## Linux解决编写脚本出现“%0D”# 安装# yum install -y dos2unix# 然后进行转化一下脚本,将其中的install_mysql.sh换成你的脚本# dos2unix ...
- python 并发编程 阻塞IO模型
阻塞IO(blocking IO) 在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 当用户进程调用了recvfrom这个系统调用,kernel内核就 ...
- mybatis多对多级联查询
1.实体 package com.govmade.govdata.modules.sys.pojo; import java.util.List; import javax.persistence.T ...
- [DS+Algo] 011 哈希
目录 1. hash 函数 2. 哈希表 3. 密码存储 1. hash 函数 关键词 任意长度输入 固定长度输出 特征 理论上输入跟输出并不是一对一 实际使用假定不会出现碰撞或者冲突 常用算法 (M ...
- mysql修改max_allowed_packet数据包最大值
在windows环境下!!!! 1.找到my.inc文件,不是你的安装目录路径,是C:\ProgramData\MySQL\MySQL Server 5.7这个路径,注意 ProgramData 文件 ...
- D - 卿学姐与魔法
卿学姐与魔法 Time Limit: 1200/800MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others) Submit Sta ...
- day16 常用模块 sys os json pickle
知识点 os:和操作系统相关sys:和解释器相关 json:和操作JSON(一种数据交换格式)相关pickle:序列化 hashlib:加密算法Collections:集合类型 ...
- Codeforces - 1203D2 - Remove the Substring (hard version) - 双指针
https://codeforces.com/contest/1203/problem/D2 上次学了双指针求两个字符串之间的是否t是s的子序列.但其实这个双指针可以求出的是s的前i个位置中匹配t的最 ...